convert form hex buffer to int using nodejs - javascript

I have a hex buffer in Node js like this:
buffer <00 E0>
I need to convert to int using little endianess. So I would read E0 00 -> 57344
For the moment I use this method:
var str = "0x" + buffer [i] .toString ('16 '). toString + buffer [i-1] .toString ('16'). toString to convert to string
var result = parseInt (str).
This method works but sometimes I get errors like this: buffer [0] = 00 but I receve 0 instead 00 or 1 instead to 01 or 10,
Is there another way to get this convertons or to solve this problem?
Thank you

Consider using the Buffer.readInt*LE or Buffer.readUInt*LE methods (the * stands for the integer size, LE for little endian). Taking your code as an example, you can use Buffer.readIntLE:
Buffer.from([ 0x00, 0xe0]).readUIntLE(0, 2)
If you have a variable buffer size:
var buffer = Buffer.from(bytes);
var result = buffer.readUIntLE(0, bytes.length) // assumes bytes.length is even

Related

when I view object as number in nodeRED debug it shows in hex

In NodeRED msg output I see hex not a number.
I have a small decode function in nodeRED. It reads a Cayenne LPP payload as a buffer object. Source of payload is a LoRaWAN temp sensor.
The hex of the payload looks like this (broken up for legibility)
010001
020000
030000
0402015A
0567011F
0665000D
0771FFA0
FFFBFC34
I'm trying to read section 5, (or Cayenne Object 05), and convert it to a temperature.
I ignore the 05 - that's the object number
I ignore the 67 - that's the bit that says 'I am a temperature value'
I use the 011F values - that's the temp that I want. I have to divide by 10.
If I convert it with calc to dec, I get 287 - which divided equals 28.7 degrees
That's correct.
My decode looks like this:
var raw = msg.payload;
buf = Buffer.from (raw, "hex");
msg.environment = new Object();
newtemp=buf.readInt16BE(15);
newtemp = newtemp / 10;
msg.environment.temp=newtemp;
return msg;
When I look at the result in the debug window I see: (reduced by me to just the temp)
0x1c.b33333333333
If I use this code instead
var raw = msg.payload;
buf = Buffer.from (raw, "hex");
newtemp=buf.readInt16BE(15);
newtemp = newtemp / 10;
var environment = {temp:newtemp};
return environment;
I get this in the debug window:
temp: 28.8
Is this something to do with inheritance?
How do I make the top code work so the msg has all data, not just a single object with the temperature?

Convert little endian binary to int in javascript on client (wscript)

I have an array of binary data that was converted using node js on server:
buffer.toString('hex');
And there are 2 integer added in the beginning of the buffer like so:
buffer.WriteInt32LE(index,0);
buffer.WriteInt32LE(id,0);
in the end i got a string like this:
var str = "1100000050000000fd2595200380024"
I need the parse this string on client, using windows scripting environment ( javascript + ActiveX)
How can i convert the first two values '11000000' and '50000000' from little endian string to integer, and the rest of the string to binary bytes represented by hex codes? In browser ArrayBuffer is avaliable, but the js executed from windows scripting environment.
var str = "1100000050000000fd25952003800245";
var int1 = parseInt(str.substring(0,7));
var int2 = parseInt(str.substring(8,15));
alert(int1);
alert(int2);
will get you the integers..
the rest of the str has 7 bytes... and a nibble... fd 25 95 20 03 80 02 4
assuming you are missing a nibble to make it 8 bytes...
var hex = [str.substring(16,str.length).length/2];
this will get you the byte array with 8 positions
var hex = [];
hex.push(str2.substring(0,2));
hex.push(str2.substring(2,4));
hex.push(str2.substring(4,6));
hex.push(str2.substring(6,8));
hex.push(str2.substring(8,10));
hex.push(str2.substring(10,12));
hex.push(str2.substring(12,14));
hex.push(str2.substring(14,16));
alert(hex);
just filled the array with the bytes in string, but you just need to convert them now :)
fullcode:
var str = "1100000050000000fd25952003800245";
var int1 = parseInt(str.substring(0,7));
var int2 = parseInt(str.substring(8,15));
var str2 = str.substring(16,str.length);
alert(int1);
alert(int2);
var hex = [];
hex.push(str2.substring(0,2));
hex.push(str2.substring(2,4));
hex.push(str2.substring(4,6));
hex.push(str2.substring(6,8));
hex.push(str2.substring(8,10));
hex.push(str2.substring(10,12));
hex.push(str2.substring(12,14));
hex.push(str2.substring(14,16));
alert(hex);

Javascript Convert int value to octet stream Array

I want convert an integer (signed) to 32 bit (big endian) into a octet stream and give the octet stream as a array value to the constructor of a
Buffer Object.
I can create it in the console for example for the value -2000:
<code>
buf = Buffer(4)
buf.writeInt32BE(-2000)
buf // is <Buffer ff ff f8 30>
buf1 = new Buffer([0xff, 0xff, 0xf8, 0x30])
</code>
The value -3000 is for example -3000 : 0xff ,0xff, 0xf4, 0x48
But the framework i use accepts not the writeInt32BE function and throws exception.
How can i convert a 32 bit integer value signed to a octet Array stream without the writeInt32BE ?
A function that takes a value and returns an array of octet stream.
Using a 4 byte array buffer, converted to a data view and calling setInt32 on the view seems to work. This approach supports specification of both little endian and big endian (the default) formats independent of machine architecture.
function bigEnd32( value) {
var buf = new ArrayBuffer(4);
var view = new DataView(buf);
view.setInt32( 0, value);
return view;
}
// quick test (in a browser)
var n = prompt("Signed 32: ");
var view = bigEnd32( +n);
for(var i = 0 ; i < 4; ++i)
console.log(view.getUint8( i));
Documentation was located searching for "MDN ArrayBuffer" "MDN Dataview" etc. Check out DataView in detail for properties that access the underlying array buffer - you may be able to tweak the code to suite your application.

JavaScript: reading 3 bytes Buffer as an integer

Let's say I have a hex data stream, which I want to divide into 3-bytes blocks which I need to read as an integer.
For example: given a hex string 01be638119704d4b9a I need to read the first three bytes 01be63 and read it as integer 114275. This is what I got:
var sample = '01be638119704d4b9a';
var buffer = new Buffer(sample, 'hex');
var bufferChunk = buffer.slice(0, 3);
var decimal = bufferChunk.readUInt32BE(0);
The readUInt32BE works perfectly for 4-bytes data, but here I obviously get:
RangeError: index out of range
at checkOffset (buffer.js:494:11)
at Buffer.readUInt32BE (buffer.js:568:5)
How do I read 3-bytes as integer correctly?
If you are using node.js v0.12+ or io.js, there is buffer.readUIntBE() which allows a variable number of bytes:
var decimal = buffer.readUIntBE(0, 3);
(Note that it's readUIntBE for Big Endian and readUIntLE for Little Endian).
Otherwise if you're on an older version of node, you will have to do it manually (check bounds first of course):
var decimal = (buffer[0] << 16) + (buffer[1] << 8) + buffer[2];
I'm using this, if someone knows something wrong with it, please advise;
const integer = parseInt(buffer.toString("hex"), 16)
you should convert three byte to four byte.
function three(var sample){
var buffer = new Buffer(sample, 'hex');
var buf = new Buffer(1);
buf[0] = 0x0;
return Buffer.concat([buf, buffer.slice(0, 3)]).readUInt32BE();
}
You can try this function.

Concatenating hex bytes and strings in JavaScript while preserving bytes

I would like to concatenate a hex value and a string using JavaScript.
var hexValue = 0x89;
var png = "PNG";
The string "PNG" is equivalent to the concatenation of 0x50, 0x4E, and 0x47.
Concatenating hexValue and png via
var concatHex = String.fromCharCode(0x89) + String.fromCharCode(0x50)
+ String.fromCharCode(0x4E) + String.fromCharCode(0x47);
...give a result with a byte count of 5 because of the first hex value needing a control character:
C2 89 50 4E 47
I am working with raw image data where I have hexValue and png and need to concatenate them without this control character being included.
Is there a way to trim off the control character?
Given I have an array of bytes, is there a better way to concatenate them and a string while preserving the bytes?
Well i was investigating and i found that in javascript to achieve this eficienly JavaScript typed arrays is used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
http://msdn.microsoft.com/en-us/library/br212485(v=vs.94).aspx
Here i wrote a code (not tested) to perform what you want:
var png = "PNG";
var hexValue = 0x89;
var lenInBytes = (png.Length + 1) * 8; //left an extra space to concat hexValue
var buffer = new ArrayBuffer(lenInBytes); //create chunk of memory whose bytes are all pre-initialized to 0
var int8View = new Int8Array(buffer); //treat this memory like int8
for(int i = 0; i < png.Length ; i++)
int8View[i] = png[i] //here convert the png[i] to bytes
//at this point we have the string png as array of bytes
int8View[png.Length] = hexValue //here the concatenation is performed
Well hope it helps.

Categories