最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting a number to a 4 bytes string - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Feb 10, 2015 at 22:00 StarFoxStarFox 1411 silver badge9 bronze badges 2
  • 2 You should probably be using Buffer instead of string. – SLaks 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 e back to you probably tomorrow to find out which method is better. – StarFox Commented Feb 10, 2015 at 23:04
Add a ment  | 

3 Answers 3

Reset to default 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>

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

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]
发布评论

评论列表(0)

  1. 暂无评论