我已經上傳了翻譯的文本。解釋不清楚。所以我添加了內容。
我想處理接收到的十六進制資料。代碼 :
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`);
});
輸出:
<Buffer 42 41 42 43 41>
66 65 66
server got: BABCA from 127.0.0.1:58107
如果'msg'變數的第1~3個引數是41 41 42 (hex), console.log("Success");
我想問這個。我該怎么辦?
uj5u.com熱心網友回復:
如果第一個到第三個引數分別是 41 41 42 的十六進制,我想輸出 Success 。我想寫這個邏輯。
if (msg[0] === 0x41 && msg[1] === 0x41 && msg[2] === 0x42) {
console.log("Success");
}
或者,由于您要比較的這些特定值對應于 ascii 字符代碼,您也可以這樣做:
if (msg.toString('ascii', 0, 3) === "AAB") {
console.log("Success");
}
uj5u.com熱心網友回復:
使用緩沖區并使用 console.log() 將值轉換為字串時,您必須注意編碼問題。當你console.log()輸入 msg 的第一個位元組時,Node 會顯示它的 ASCII 值。要查看十六進制值,您需要使用 將位元組轉換為其十六進制值toString(16)。這告訴節點顯示位元組的基數 16(十六進制)值。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/402095.html
