javascript Buffer from several variables - javascript

How is it possible in javascript to obtain the b Buffer in a way simpler than the following?
var num=6553599
var a = new Buffer(4);
a.writeInt32LE(num);
var up=a.readUInt8(2);
var mid=a.readUInt8(1);
var low=a.readUInt8(0);
var b=new Buffer(6);
b.writeUInt8('T'.charCodeAt(0),0);
b.writeUInt8(up ,1);
b.writeUInt8(mid ,2);
b.writeUInt8(low ,3);
b.writeUInt8(0 ,4);
b.writeUInt8(1 ,5);

If performance is not an issue you can use the string representation of buffers to work with them more easily.
Usually I prefer the hex representation of buffers since they're easier to read and it is easy to count bytes this way.
var bConcat = (a, b) => new Buffer(a.toString("hex") + b.toString("hex"), "hex");
var reducer = (acc, current)=> bConcat(acc, current);
var num=6553599
var a = new Buffer(4);
var t = 'T'.charCodeAt(0);
a.writeInt32LE(num);
var head = new Buffer(t.toString(16), "hex");
var tail = new Buffer("0001", "hex");
var b = [head, a.slice(0,3).reverse(), tail].reduce(reducer);

Related

Getting 6.33 from an equation in Javascript when it should output 8.99

I'm doing some simple math in Javascript, but my equation's result is drastically different than what it should be. The math is:
3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1;
When I did it out by hand, and then used Wolfram Alpha (https://www.wolframalpha.com/) I get the correct result of 8.99. However, when I use the equation in Javascript I mysteriously get 6.33
The actual equation looks like
VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2;
but I removed all the variables in an attempt to debug (I thought it might be some error where I needed parseInt)
Here are the whole functions for reference
function calc(){
var temp = 0;
var total = 0;
for(i = 0; i<sArr.length; i++){
total = total + calc2(i);
}
var o = document.getElementById("output");
o.value = total;
}
function calc2(i){
var s = document.getElementById("s"+i);
var g = document.getElementById("g"+i);
var t = document.getElementById("t"+i);
var VO2walkmin = 3.28;
var VO2rest = 3.05;
var C1 = 0.32;
var C2 = 0.19;
var C3 = 2.66;
var Cdecline = 0.73;
var s2 = s.value;
var g2 = g.value;
var t2 = t.value;
var negGrade = g.value;
if(g2 < 0){g2 = 0};
//VO2move = ((C1 * g2)+VO2walkmin)+((1+(C2*g2))*(C3*s2^2)); //ORIGINAL TRANSCRIPTION
//VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2; // TRANSLATED FROM COPY PASTE
VO2move = 3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1; // COPY - PASTED FROM EXCEL
return VO2move;
}
Even naked numbers I still get the output of 6.33. I'm totally puzzled, and any help is appreciated.
You need to take the power (exponentiation) operator ** instead of the bitwise XOR operator ^.
console.log(3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1**2))*1);

Convert a byteArray into an IntegerArray using javascript

I receive a bytearray and I want to convert it into a intarray.
Is this possible in NodeJS?
Reason to do that:
A proxy receives values from a serialconnection which is a bytearray and I try to decode that and put it into a more specific JSON object.
var uint8Message = new Uint8Array(8),
output = [];
uint8Message[0] = 40;
uint8Message[1] = 40;
uint8Message[2] = 40;
uint8Message[3] = 40;
uint8Message[4] = 40;
uint8Message[5] = 40;
uint8Message[6] = 40;
uint8Message[7] = 40;
var counter = 0;
var intermediate = [];
for (var i = 0; i< uint8Message.byteLength; i++) {
if (counter < 4) {
intermediate.push(uint8Message[i]);
}
counter++;
if (counter === 3 ){
output.push(new Uint16Array(intermediate));
counter = 0;
intermediate = [];
}
}
console.log(output);
I am sending a intArray which is converted to byteArray from arduino to a NodeJS serialport handler. I want to get 8 integer values in array:
Status and value for four engines.
So in the end I want to have this:
[1,89,2,49,1,28,3,89]
Which is not complete correct with the example. But the example above is for testing.
Still not sure I understand your question correctly but if you want to convert Uint8Array to say Uint32Array you could do
const uint8Array = new Uint8Array(8).fill(40)
console.log(new Uint32Array(uint8Array.buffer))
If you need plain old js array you could do
const uint8Array = new Uint8Array(8).fill(40)
const intArray = Array.from(new Uint32Array(uint8Array.buffer))
console.log(Array.isArray(intArray))
Also you might want to take a look at what is called DataView that allows low level access to buffers' contents.

Adding values concatenating

Instead of "var instance = ..." adding the two values it concatenates them. Can anyone suggest what I need to fix?
I'm trying to add "var startingEmail" value and "var k".
Thank you for your help!
var startingEmail = sheet.getRange("C2").getDisplayValue();
var numEmails = sheet.getRange("E2").getDisplayValue();
var max = numEmails;
for (var k = 0; k<max; ++k){
var threads = GmailApp.getInboxThreads(startingEmail,max)[k]; //get max 50 threads starting at most recent thread
var messages = threads.getMessages()[0];
var sndr;
var rcpnt;
var srAry = [];
var sndr = messages.getFrom().replace(/^.+<([^>]+)>$/, "$1"); //http://stackoverflow.com/questions/26242591/is-there-a-way-to-get-the-specific-email-address-from-a-gmail-message-object-in
var sndrLower = sndr.toLowerCase;
var rcpnt = messages.getTo().replace(/^.+<([^>]+)>$/, "$1");
var rcpntLower = rcpnt.toLowerCase;
var cc = messages.getCc().replace(/^.+<([^>]+)>$/, "$1");
var ccLower = cc.toLowerCase;
//srAry.push(sndr);
//srAry.push(rcpnt);
//srAry.push(cc);
var isIn = joinAddr.search(sndr || rcpnt);
if(isIn == -1){
var instance = k;
I can't see the example in your code but it sounds like you can just wrap Number() around your variable and it will perform the type conversion so the code will perform the math instead of concatenating as strings.

Javascript BigInt.js How to Divide big numbers

http://www.leemon.com/crypto/BigInt.js
I am using the leemon bigint.js library, but I am having trouble figuring out how to divide one big number by another. Here is what I have so far:
var a = str2bigInt("100",10);
var b = int2bigInt("5", 10);
var result = [];
var r = [];
divide_(a,b,result,r)
alert(bigInt2str(result,10));
but when I alert(result) the output is 0. The result should be 20? Can anybody see what I am doing wrong?
Cheers
I suppose the line
var b = int2bigInt("5", 10);
should be
var b = str2bigInt("5", 10);
The function int2bigInt expects an integer, not a string.
Apparently, this BigInt.js library expects the result arrays to already have sufficient length to store the result; using empty arrays doesn't work.
This code however works as expected:
var a = str2bigInt("100",10);
var b = int2bigInt("5", 10);
var result = new Array(2);
var r = new Array(2);
divide_(a,b,result,r);
alert(bigInt2str(result,10));

Transform a string into array using javascript

I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.

Categories