2

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.

2
  • 2
    You should probably be using Buffer instead of string. Commented Feb 10, 2015 at 22:01
  • Thanks for your answers I'm having issues with the par of my script that is supposed to send the TCP packet, I'll come back to you probably tomorrow to find out which method is better. Commented Feb 10, 2015 at 23:04

3 Answers 3

4

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.