【JavaScript】Hardware communication data verification BCC XOR verification generation bitwise inversion hexadecimal data formatting

Hexadecimal (abbreviated as hex or subscript 16) is a counting system with a base of 16, and it is a [carry system] that enters 1 every 16. Usually represented by numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F (a, b, c, d, e, f), Among them: A F represents 10 15.

Binary (abbreviated as bin ) is a counting system with a base of 2, and it is a [carry system] in which every 2 enters 1. Usually represented by numbers 0 and 1.

When connecting with hardware, you will often encounter base conversion and data verification. The computer and hardware will use two different endian modes, and data conversion also needs to be adjusted accordingly.

Here are two functions that handle hexadecimal formatting and BCC verification, supporting browser environment, applet environment, and node server.

I have used these two functions in the applet to connect to the hardware device, connect through Bluetooth, and subscribe to obtain the data sent by the device. Usually, what is returned on the hardware is not the commonly used json format, but a continuous hexadecimal data. We need to verify the head, tail and front of the returned data to ensure that the received data is complete, and then pass the verification. The data is parsed again to obtain the information we need to process, which can be a json, or a number, etc.

hex format

function formatHex(s) {
    
    
    if (s.indexOf(' ') < 0 && s.length % 2 === 1) {
    
    
        s = '0' + s;
    }
    s = s.replace(/(\w{2})(?=[^ ])/gim, "$1 ")
    s = s.replace(/^(\w) /gim, "0$1 ")
    s = s.replace(/ (\w)$/gim, " 0$1")
    s = s.replace(/ (\w) /gim, " 0$1 ")
    s = s.replace(/ (\w) /gim, " 0$1 ")
    return s;
}

BCC check generation

function createBBC(text) {
    
    
    text = formatHex(text)
    text = text.split(' ')
    let sum = 0
    let count = 0
    for (let i = 0; i < text.length; i++) {
    
    
        if (text[i] !== "" && text[i] !== " ") {
    
    
            let val = parseInt(text[i], 16)
            sum = sum  + val;
            count++;
        }
    }
    console.log("结果",sum,count,text)
    let bbc = (255-sum).toString(16)
    console.log("取反",bbc)
    return bbc.toUpperCase()
}

Guess you like

Origin blog.csdn.net/sky529063865/article/details/125297917