Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading signed 16 bit data in Javascript

Tags:

javascript

I have been banging my head to solve this:

I received a raw data from an embeded device. From the documentation, the way to read it into a single value is:

Every two bytes of data can be combined to a single raw wave value.Its value is a signed 16-bit integer that ranges from -32768 to 32767. The first byte of the Value represents the high-order byte of the twos-compliment value, while the second byte represents the low-order byte. To reconstruct the full raw wave value, simply shift the first byte left by 8 bits, and bitwise-or with the second byte.

short raw = (Value[0]<<8) | Value[1];

One of the 2 bytes that I received is "ef". When I used the bitwise operation above the result does not seems right as I noticed I never get a single negative value (its ECG data, negative values are normal). I believe using Javascript to do this is not straight forward. The way I did it was like this:

var raw = "ef"; // just to show one. Actual one is an array of this 2 bytes but in string.
var value = raw.charAt(0) << 8 | raw.charAt(1)

Please Advice. Thanks!

EDIT:

I also did like this:

let first = new Int8Array(len); // len is the length of the raw data array
let second = new Int8Array(len);
let values = new Int16Array(len) // to hold the converted value

for(var i=0; i<len ; i++)
{
   //arr is the array that contains the every two "characters"
   first[i] = arr[i].charAt(0);
   second[i] = arr[i].charAt(1);
   values[i] = first[i] << 8 | second[i];  
}

But still all is positive result. no negative. Can someone verify if I am doing this correctly, just in case maybe the values are actually all positive :p

like image 326
Binbo Avatar asked Nov 01 '25 13:11

Binbo


1 Answers

You can use property that the string is already 16 bit and then make it signed.
Also instead of reading 8bit at time just read one unsigned 16bit using charCodeAt.

var raw = "\u00ef"; //original example
var buf = new Int16Array(1);
buf[0] = raw.charCodeAt(0); //now in the buf[0] is typed 16 bit integer
//returns 239, for \uffef returns -17

var raw = "\uffef"; //original example
var buf = new Int16Array(1);
buf[0] = raw.charCodeAt(0); //now in the buf[0] is typed 16 bit integer
console.log(buf[0])
 
like image 133
Evil Avatar answered Nov 04 '25 04:11

Evil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!