0

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

Bhojendra Rauniyar
86.1k36 gold badges179 silver badges241 bronze badges
asked Sep 8, 2014 at 9:47
2
  • Blind guess: The C# version is using a signed integer, your code emulates an unsigned integer. Commented Sep 8, 2014 at 9:49
  • @DanFromGermany thanks.. what I can do for this in JS? Commented Sep 8, 2014 at 9:51

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.