在nodejs中的tcp套接字上将十六进制字节转换为十进制接收

s71maibg  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(421)

我正在tcp套接字上接收000F313233343536373839393303132333435作为字节,并希望将其转换为123456789012345我希望将套接字上接收的此字节流解析为数字。

function onConnect(socket) {
    socket.setEncoding('utf8');//Socket data to utf8 format

    socket.on('data', function (data) { //Socket event when data is sent from tcp client
    var buffer = Buffer.from(data,"hex");

        let clientport=socket.remotePort;
        let clientadd=socket.remoteAddress;
        console.log(clientadd+":"+clientport)

        console.log("--",data,"--")

        console.log(buffer);
        var msg = buffer.toString()
        var msglength = msg.length;
        console.log(msglength);

    })//<=on data
d7v8vwbk

d7v8vwbk1#

如果你知道你的号码永远适合你 Number.MAX_SAFE_INTEGER 你可以使用简单的 Number 转换:

const src = Buffer.from('000F313233343536373839303132333435', 'hex');

const hex = src.toString('utf8', 2); // strip first 2 header bytes 000F

console.log(Number(hex)); // 123456789012345

或是 BigInt 如果可以是任意长度的整数:

const bigSrc = Buffer.from(
  '000F313233343536373839303132333435313233343536373839303132333435313233343536373839303132333435',
  'hex'
);

const bigStr = bigSrc.toString('utf8', 2); // strip first 2 header bytes 000F

console.log(BigInt(bigStr)); // 123456789012345123456789012345123456789012345n

stackblitz链接

相关问题