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
Bhojendra Rauniyar
86.1k36 gold badges179 silver badges241 bronze badges
asked Sep 8, 2014 at 9:47
Umesh Sehta
10.7k5 gold badges43 silver badges68 bronze badges
2 Answers 2
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
answered Sep 8, 2014 at 9:52
Bhojendra Rauniyar
86.1k36 gold badges179 silver badges241 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Sep 8, 2014 at 10:09
Nikolas
1,1761 gold badge6 silver badges11 bronze badges
Comments
lang-js
signed integer, your code emulates anunsigned integer.