For an AJAX request, I need to send a magic number as the first four bytes of the request body, most significant byte first, along with several other (non-constant) values in the request body. Is there something equivalent to htonl in JavaScript?
For example, given 0x42656566, I need to produce the string "Beef". Unfortunately, my number is along the lines of 0xc1ba5ba9. When the server reads the request, it is getting the value -1014906182 (instead of -1044751447).
For an AJAX request, I need to send a magic number as the first four bytes of the request body, most significant byte first, along with several other (non-constant) values in the request body. Is there something equivalent to htonl in JavaScript?
For example, given 0x42656566, I need to produce the string "Beef". Unfortunately, my number is along the lines of 0xc1ba5ba9. When the server reads the request, it is getting the value -1014906182 (instead of -1044751447).
Share Improve this question edited Feb 14, 2012 at 22:52 Tommy McGuire asked Feb 14, 2012 at 19:36 Tommy McGuireTommy McGuire 1,25313 silver badges17 bronze badges 1- This may help: i-programmer.info/programming/javascript/… – Diodeus - James MacFarlane Commented Feb 14, 2012 at 19:45
2 Answers
Reset to default 4There's no built-in function, but something like this should work:
// Convert an integer to an array of "bytes" in network/big-endian order.
function htonl(n)
{
// Mask off 8 bytes at a time then shift them into place
return [
(n & 0xFF000000) >>> 24,
(n & 0x00FF0000) >>> 16,
(n & 0x0000FF00) >>> 8,
(n & 0x000000FF) >>> 0,
];
}
To get the bytes as a string, just call String.fromCharCode
on each byte and concatenate them:
// Convert an integer to a string made up of the bytes in network/big-endian order.
function htonl(n)
{
// Mask off 8 bytes at a time then shift them into place
return String.fromCharCode((n & 0xFF000000) >>> 24) +
String.fromCharCode((n & 0x00FF0000) >>> 16) +
String.fromCharCode((n & 0x0000FF00) >>> 8) +
String.fromCharCode((n & 0x000000FF) >>> 0);
}
Simplified version http://jsfiddle/eZsTp/ :
function dot2num(dot) { // the same as ip2long in php
var d = dot.split('.');
return ((+d[0]) << 24) +
((+d[1]) << 16) +
((+d[2]) << 8) +
(+d[3]);
}
function num2array(num) {
return [
(num & 0xFF000000) >>> 24,
(num & 0x00FF0000) >>> 16,
(num & 0x0000FF00) >>> 8,
(num & 0x000000FF)
];
}
function htonl(x)
{
return dot2num(num2array(x).reverse().join('.'));
}
var ipbyte = dot2num('12.34.56.78');
alert(ipbyte);
var inv = htonl(ipbyte);
alert(inv + '=' + num2array(inv).join('.'));