Reputation: 141
How can I convert a number like 5 into a 4 bytes string that would resemble something like this if it were to be entered manually.
var size = "\00\00\00\05";
The number is the size of a packet I need to send through a socket and the first 4 bytes of the packet needs to be the size of the packet (without counting the first 4 bytes obviously).
var size = "\00\00\00\05";
var packet = size + "JSON_STRING";
Let me know if I'm not explaining myself properly I have never used node.js before but I'm getting the hang of it.
Upvotes: 2
Views: 2942
Reputation: 161457
Use Node's Buffer
rather than a string. Strings are for characters, Buffers are for bytes:
var size = 5;
var sizeBytes = new Buffer(4);
sizeBytes.writeUInt32LE(size, 0);
console.log(sizeBytes);
// <Buffer 05 00 00 00>
Upvotes: 4
Reputation: 36703
You can do this using JavaScript Typed arrays, this allows actual byte level control rather than using characters within Strings...
Create an ArrayBuffer
var ab = new ArrayBuffer(4);
Use DataView to write an integer into it
var dv = new DataView(ab);
dv.setInt32(0, 0x1234, false); // <== false = big endian
Now you can get your ArrayBuffer as an unsigned byte array
var unit8 = new Uint8Array(ab);
Output
console.log(unit8);
[0, 0, 18, 52]
Upvotes: 2
Reputation: 24146
One obvious variant is:
var size = 5;
var b1 = size & 0xff;
var b2 = (size>>>8) & 0xff;
var b3 = (size>>>16) & 0xff;
var b4 = (size>>>24) & 0xff;
var sizeString = String.fromCharCode(b1, b2, b3, b4);
very important note - depending on architecture order of b1-b4 could be different, it is called Endianness and probably you need b4, b3, b2, b1
Upvotes: 2