jemz
jemz

Reputation: 5143

Convert binary to hex in node.js

I want to ask I want to convert my binary data to hex before I will insert this to my table.

var net  = require('net');

var server = net.createServer(function(socket){

    socket.on('data',function(data){
    var bindata= data.toString('binary');

    //filter(bindata);

    //if no error convert to hex.
    var hexdata = bindata.toString('hex');

    //insert hexdata here.
});

server.listen(3030,'127.0.0.1', function () {
    console.log("server is listenining");
});

but the problem is that the binary data will be inserted.

Upvotes: 3

Views: 17065

Answers (2)

sudam
sudam

Reputation: 101

Try this:

parseInt("1111", 2).toString(16);

Second param in parseInt is radix its represent "111" value to binary and toString(16) convert it to hex.

Upvotes: 0

Amadan
Amadan

Reputation: 198466

parseInt("10101001", 2).toString(16)
// => "a9"

EDIT: I think I misunderstood the question. Your data starts out as Buffer, then you convert it to a string, then you want it as hex? If so, just do data.toString('hex'). If you have already manipulated bindata, then reconstruct into a buffer:

var bindata = data.toString('binary');
// do something with bindata
var hexdata = new Buffer(bindata, 'ascii').toString('hex');

Upvotes: 13

Related Questions