Umesh Sehta
Umesh Sehta

Reputation: 10683

convert array value into integer

I am trying to convert bytes to integer number value its working for non negative value but not for negative value. Here is my code:-

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


  byteArrayToLong([158,175,59,0]);  //3911582 correct 
  byteArrayToLong([229,93,138,255])//4287258085 incorrect the correct value is (i.e from c# BitConverter.ToInt32() method)  -7709211

JSFiddle Demo

Upvotes: 0

Views: 92

Answers (2)

Nikolas
Nikolas

Reputation: 1176

C-Link Nepal's solution is very elegant. Here is a more verbose one: You are clearly trying to treat the byte array as a two's complement representation of a number. You have to take into account, that the first bit of the highest byte depicts the sign. Therefore, you should treat the first byte seperatly:

var byteArrayToLong = function (byteArray) {
  var value = 0, firstByteOffset = byteArray.length - 1;
  if (byteArray[firstByteOffset] >= 127) {
    value = byteArray[firstByteOffset] - 256;
  } else {
    value = byteArray[firstByteOffset];
  }
  for (var i = firstByteOffset - 1; i >= 0; i--) {
    value = (value * 256) + byteArray[i];
  }
  console.log(value);
  return value;
};


byteArrayToLong([158,175,59,0]);  // 3911582
byteArrayToLong([229,93,138,255]); // -7709211 

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

There is very simple way to convert a value to an integer like below:

var val = 23.234;
console.log(~~val) // ~~ to convert into an integer

You may use this in your conversion...


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


  byteArrayToLong([158,175,59,0]); //3911582
  byteArrayToLong([229,93,138,255]) //-7709211

Upvotes: 4

Related Questions