首页 > 编程语言 >校验和算法 rd16

校验和算法 rd16

时间:2023-03-02 17:04:23浏览次数:40  
标签:rd16 Buffer checksum 校验 算法 let 256 buf

rand digest 16bit

const modulus16 = 256 * 256;
const rd16 = t => {
    let buf = Buffer.isBuffer(t) ? t : Buffer.from(t);
    let p = Math.floor(buf.length / 2);
    let r = buf.length % 2;
    let checksum = 0;
    for (let i = 0; i < p; i += 2) {
        checksum = (checksum + buf[i] * 256 + buf[i + 1]) % modulus16;
    }
    if(r === 1) {
        checksum = (checksum + buf[p]) % modulus16;
    }
    buf = Buffer.allocUnsafe(2);
    buf[0] = Math.floor(checksum / 256);
    buf[1] = checksum % 256;
    return buf;
};
console.log(rd16('hello world!'));  //<Buffer 43 f1>

标签:rd16,Buffer,checksum,校验,算法,let,256,buf
From: https://blog.51cto.com/u_13128132/6096456

相关文章