javascript network-programming endianness

JavaScript equivalente a htonl?



network-programming endianness (2)

No hay función incorporada, pero algo como esto debería funcionar:

// 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, ]; }

Para obtener los bytes como una cadena, solo llame a String.fromCharCode en cada byte y concatenarlos:

// 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); }

Para una solicitud AJAX, necesito enviar un número mágico como los primeros cuatro bytes del cuerpo de la solicitud, el byte más significativo primero, junto con varios otros valores (no constantes) en el cuerpo de la solicitud. ¿Hay algo equivalente a htonl en JavaScript?

Por ejemplo, dado 0x42656566, necesito producir la cadena "Beef". Desafortunadamente, mi número está en la línea de 0xc1ba5ba9. Cuando el servidor lee la solicitud, obtiene el valor -1014906182 (en lugar de -1044751447).


Versión simplificada http://jsfiddle.net/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(''.''));