简体   繁体   中英

Convert Hex bytes to Decimal receving on TCP Socket in NODeJS

I am receving 000F313233343536373839303132333435 as bytes on my tcp socket and want to convert it to 123456789012345 I want to parse this bytes stream receving on the socket to to the number.

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

If you know your number will always fit into Number.MAX_SAFE_INTEGER you can use simple Number conversion:

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

Or to the BigInt if it could be an integer of arbitrary length:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM