在 NODe JS 中的 TCP 套接字上将十六进制字节转换为十进制接收

Convert Hex bytes to Decimal receving on TCP Socket in NODeJS

我正在接收 000F313233343536373839303132333435 作为我的 TCP 套接字上的字节,并希望将其转换为 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

如果您知道您的号码将始终适合 Number.MAX_SAFE_INTEGER,您可以使用简单的 Number 转换:

const HEADER_LEN = 2;

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

const len = src.readUInt16BE();
const hex = src.toString('utf8', HEADER_LEN, HEADER_LEN + len); // skip first 2 header bytes

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

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

const bigSrc = Buffer.from(
  '002D313233343536373839303132333435313233343536373839303132333435313233343536373839303132333435',
  'hex'
);

const bigLen = bigSrc.readUInt16BE();
const bigStr = bigSrc.toString('utf8', HEADER_LEN, HEADER_LEN + bigLen); // skip first 2 header bytes

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

stackblitz link