php实现CRC校验 适用于MODBUS协议

php 复制代码
function CRC16($string)
    {
        $crcBytes = [];
            for ($i = 0; $i < strlen($string); $i += 2) {
                $crcBytes[] = hexdec(substr($string, $i, 2));
            }
            $crc = 0xFFFF;
            $polynomial = 0xA001;  // This is the polynomial x^16 + x^15 + x^2 + 1
    
            foreach ($crcBytes as $byte) {
                $crc ^= $byte;
                for ($i = 0; $i < 8; $i++) {
                    if ($crc & 0x0001) {
                        $crc = (($crc >> 1) ^ $polynomial) & 0xFFFF;
                    } else {
                        $crc >>= 1;
                    }
                }
            }
            return $crc;
    }

调用

php 复制代码
$ru = $this->CRC16($str2);

我对接MODBUS 协议 最后校验位是需要 转16进制后 调换位置

php 复制代码
 $ru = str_pad(dechex($ru), 4, '0', STR_PAD_LEFT);
 $str2 = $str2.substr($ru,-2).substr($ru,0,2);

相当于 后两位在前 , 前两位在后

感谢观看文章,

相关推荐
云游云记1 小时前
PHP 汉字转拼音扩展包:overtrue/pinyin 全面指南
php·overtrue/pinyin
有代理ip2 小时前
成功请求的密码:HTTP 2 开头响应码深度解析
java·大数据·python·算法·php
小白学大数据5 小时前
实测数据:多进程、多线程、异步协程爬虫速度对比
开发语言·爬虫·python·php
会开花的二叉树6 小时前
Reactor网络库的连接管理核心:Connection类
开发语言·网络·php
木子啊7 小时前
PHP中间件:ThinkCMF 6.x核心利器解析
开发语言·中间件·php
Big Cole8 小时前
PHP面试题(核心基础篇:垃圾回收+自动加载)
android·开发语言·php
Diros1g9 小时前
ubuntu多网卡网络配置
网络·ubuntu·php
catchadmin9 小时前
PHP 现在可以零成本构建原生 iOS 和 Android 应用 NativePHP for Mobile v3 发布
android·ios·php
子木鑫9 小时前
[SUCTF 2019] CheckIn1 — 利用 .user.ini 与图片马构造 PHP 后门并绕过上传检测
android·开发语言·安全·php
JSON_L10 小时前
使用 SQLite 创建数据库和表
数据库·sqlite·php