Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting javascript Integer to byte array and back

Tags:

javascript

People also ask

Can int be converted to byte?

It's not possible. A byte is 0 to 255. An int is a whole lot bigger than that. So, you can convert an int to a stream of bytes, but not to a byte.

Can you convert number to array in JavaScript?

Typecast the integer into a string. Using the split() method to make it an array of strings. Iterate over that array using the map() method. Using the map() method returns the array of strings into an array of Integers.

What happens when we convert int to byte in Java?

The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte). Also, remember this method does override byteValue() method of the Number class.

What is byte array in JavaScript?

An array of bytes is known as an array buffer in javascript while known as a “byte array” in some other languages. The ArrayBuffer object represents a fixed-length raw binary data buffer whose content can't be altered directly.


Using the hint provided by Susanoh13, here are the two functions that allow conversion of number from/to ByteArray:

longToByteArray = function(/*long*/long) {
    // we want to represent the input as a 8-bytes array
    var byteArray = [0, 0, 0, 0, 0, 0, 0, 0];

    for ( var index = 0; index < byteArray.length; index ++ ) {
        var byte = long & 0xff;
        byteArray [ index ] = byte;
        long = (long - byte) / 256 ;
    }

    return byteArray;
};

byteArrayToLong = function(/*byte[]*/byteArray) {
    var value = 0;
    for ( var i = byteArray.length - 1; i >= 0; i--) {
        value = (value * 256) + byteArray[i];
    }

    return value;
};

In JavaScript bit shifts (>>, <<) are always performed on signed, 32-bits integers. This leads to range overflow for large numbers.


try (** is power operator, << and >>> are bit-shift operators) - intFromBytes works only for arrays generated from positive integers

function getInt64Bytes(x) {
  let y= Math.floor(x/2**32);
  return [y,(y<<8),(y<<16),(y<<24), x,(x<<8),(x<<16),(x<<24)].map(z=> z>>>24)
}

function intFromBytes(byteArr) {
    return byteArr.reduce((a,c,i)=> a+c*2**(56-i*8),0)
}

function getInt64Bytes(x) {
  let y= Math.floor(x/2**32);
  return [y,(y<<8),(y<<16),(y<<24), x,(x<<8),(x<<16),(x<<24)].map(z=> z>>>24)
}

function intFromBytes(byteArr) {
    return byteArr.reduce((a,c,i)=> a+c*2**(56-i*8),0)
}


// TEST

let n = 40*2**40 + 245*2**32 + 194*2**24 + 143*2**16 + 92*2**8 + 40;
let b = getInt64Bytes(n);
let i = intFromBytes(b);

console.log(`number      : ${n}`);
console.log(`int to bytes: [${b}]`);
console.log(`bytes to int: ${i}`);

Brainfuck-style Lodash version. Just 4 lulz! don't use it!

const uintToArray = (uint, size) => _.chunk(_.padStart(uint, size*2,  0).split(''), 2).map((a)=>parseInt(a[0]+a[1]))