Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript equivalent to htonl?

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).

like image 695
Tommy McGuire Avatar asked Jun 08 '26 12:06

Tommy McGuire


1 Answers

There'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);
}
like image 93
Matthew Crumley Avatar answered Jun 11 '26 21:06

Matthew Crumley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!