I have uploaded the translated text. The explanation is not clear. So I add the content.
I want to handle the received HEX data. code :
server.on('message', (msg, rinfo) => {
console.log(msg)
console.log(msg[0] " " msg[1] " " msg[2])
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}\n`);
});
output:
<Buffer 42 41 42 43 41>
66 65 66
server got: BABCA from 127.0.0.1:58107
If the 1st~3rd argument of the 'msg' variable is 41 41 42 (hex), console.log("Success");
I wanted to ask this. What should I do?
CodePudding user response:
I want to output Success if the 1st to 3rd arguments are 41 41 42 in hexadecimal, respectively. I want to write this logic.
if (msg[0] === 0x41 && msg[1] === 0x41 && msg[2] === 0x42) {
console.log("Success");
}
Or, since these particular values you are comparing to correspond to ascii character codes, you could also do this:
if (msg.toString('ascii', 0, 3) === "AAB") {
console.log("Success");
}
CodePudding user response:
When using buffers and converting values to strings using console.log() you have to be careful of encoding issues. When you console.log()
the first byte of msg, Node displays the ASCII value of it. To see the hex value, you need to convert the byte to its hex value using toString(16)
. This tells node to display the base 16 (hex) value of the byte.
const msg = Buffer.from('4241424341', 'hex');
console.log(msg);
console.log('Hex encode first byte of msg: ' msg.toString('hex',0,1));
console.log('ASCII encode first byte of msg: ' msg.toString('ascii',0,1));
console.log('Hex of msg[0]: ' msg[0].toString(16));
console.log('ASCII code of msg[0]: ' msg[0]);
const firstThree = msg.slice(0, 3);
const compareBuffer = Buffer.from('424142', 'hex');
console.log(firstThree);
console.log(compareBuffer)
const isSuccess = compareBuffer.equals(firstThree);
console.log(isSuccess);