nodejs convert decimal to hex(00-00) and reverse? - node.js

So I want to send a hex value to a service. The problem is that the service want this hex value in a specific format, 00-00, and also reversed.
For Example, when I want to tell the Service I want tag '1000':
1000 dec is 3E8 in hex. easy.
Now the service wants the format 03-E8.
Also the service reads from right to left so the final value would be E8-03.
Another example, '3' would be 03-00.
Edit:
I forgott to say that I dont need it as string, but as Uint8Array. So I would create the final result with new Uint8Array([232, 3]). (Eaquals E8-03 = 1000)
So the question in general is: How can I get a [232,3] from an input of 1000 or [3, 0] from 3?
Is there a build in methode or a pakage that already can do this convertion?

There's probably a much simpler way, but here is a simple solution.
Edit: If you need at least two pairs, you can change the first argument of padStart.
function dec2hexUi8Arr (n) {
const hex = (n).toString(16);
const len = hex.length;
const padLen = len + (len % 2);
const hexPad = hex.padStart(Math.max(padLen, 4), '0');
const pairs = hexPad.match(/../g).reverse().map(p => parseInt(p, 16));
const ui8Arr = new Uint8Array(pairs);
return ui8Arr;
}
const vals = [
1000,
3,
65536
].map(dec2hexUi8Arr);
console.log (vals);

I don't know any tool or package. I would do something like this:
const a = 1000;
const a0 = a % 256;
const a1 = Math.floor(a / 256);
const arr = new Uint8Array([a0, a1]);
console.log(arr);
const arrStr = []
arr.forEach((elem) => {
const str = elem.toString(16).toUpperCase();
if (str.length === 2) {
arrStr.push(str);
} else {
arrStr.push('0' + str)
}
});
console.log(arrStr.reverse().join('-'));
Output:
Uint8Array(2) [ 232, 3 ]
03-E8

Related

parameter from package.json script (Encoding problem)

https://nodejs.org/docs/latest/api/process.html#processargv
https://www.golinuxcloud.com/pass-arguments-to-npm-script/
passing a parameter by invoking a script in package.json as follows:
--pathToFile=./ESMM/Parametrização_Dezembro_PS1_2022.xlsx
in code retrieve that parameter as argument
const value = process.argv.find( element => element.startsWith( `--pathToFile=` ) );
const pathToFile=value.replace( `--pathToFile=` , '' );
The string that's obtain seems to be in the wrong format/encoding
./ESMM/Parametrização_Dezembro_PS1_2022.xlsx
I tried converting to latin1 (other past issues were fixed with this encoding)
const latin1Buffer = buffer.transcode(Buffer.from(pathToFile), "utf8", "latin1");
const latin1String = latin1Buffer.toString("latin1");
but still don't get the string in the correct encoding:
./ESMM/Parametriza?º?úo_Dezembro_PS1_2022.xlsx
My package.json is in UTF-8.
My current locale is (chcp): Active code page: 850
OS: Windows
This seems to be related to:
https://code.visualstudio.com/docs/editor/tasks#_changing-the-encoding-for-a-task-output
vs code, how to change encoding for terminal triggered by "build task"
https://pt.stackoverflow.com/questions/148543/como-consertar-erro-de-acentua%C3%A7%C3%A3o-do-cmd
Get argv raw bytes in Node.js
will try those configurations
const min = parseInt("0xD800",16), max = parseInt("0xDFFF",16);
console.log(min);//55296
console.log(max);//57343
let textFiltered = "",specialChars = 0;
for(let charAux of pathToFile){
const hexChar = Buffer.from(charAux, 'utf8').toString('hex');
console.log(hexChar)
const intChar = parseInt(hexChar,16);
if(hexChar.length > 2){
//if(intChar>min && intChar<max){
//console.log(Buffer.from(charAux, 'utf8').toString('hex'))
specialChars++;
console.log(`specialChars(${specialChars}): ${hexChar}`);
}else{
textFiltered += String.fromCharCode(intChar);
}
}
console.log(textFiltered); //normal characters
./ESMM/Parametrizao_Dezembro_PS1_2022.xlsx
console.log(specialChars(${specialChars}): ${hexChar}); //specialCharacters
specialChars(1): e2949c
specialChars(2): c2ba
specialChars(3): e2949c
specialChars(4): c3ba
seems that e2949c hex value to indicate a special character since it repeats and 0xc2ba should be able to convert to "ç" and 0xc3ba to "ã" idealy still trying to figure that out.
Each Unicode codepoint can be written in a string with \u{xxxxxx} where xxxxxx represents 1–6 hex digits
As #JosefZ indicated but for Python, in my case gona use a direct conversion since will alls have the keyword "Parametrização" as part of the parameter.
The probleam that encountered in this case is that my package.json and my script are in the correct format UTF8 as stated by #tripleee (thanks for the help providade) but process.argv that returns <string[]> that basicaly UTF16... so my solution is deal with the ├ that in hex is "e2949c" and retrive the correct characters:
const UTF8_Character = "e2949c" //├
//for this cases use this json/array that haves the correct encoding
const personalized_encoding = {
"c2ba": "ç",
"c3ba": "ã"
}
let textFiltered = "",specialChars = 0;
for(let charAux of pathToFile){
const hexChar = Buffer.from(charAux, 'utf8').toString('hex');
//console.log(hexChar)
const intChar = parseInt(hexChar,16);
if(hexChar.length > 2){
if(hexChar === UTF8_Character) continue;
specialChars++;
//console.log(`specialChars(${specialChars}): ${hexChar}`);
textFiltered += personalized_encoding[hexChar];
}else{
textFiltered += String.fromCharCode(intChar);
}
}
console.log(textFiltered);

How to add Numbers In Arrays format if we have a word in 3 files using nodejs

I want to ask a question, what is it, I have three files, if there is a Word COMMON in those files then it should be printed like this [1,2 3], otherwise, if there is a word in 1 and 2 then it should be printed like this [1 2] , I Tried to PUSH ARRAY but it's not happening
Here Is My Code:
let Page1data = filtered.map((val) => {
let data = {};
if (Page1.includes(val)) {
data[val] = ["1"];
}
if (Page2.includes(val)) {
data[val] = ["2"];
}
if (Page3.includes(val)) {
data[val] = ["3"];
}
return data;
});
console.log(Page1data);
If I get it right, the problem is with your declaration.
.push() is for arrays not for objects. You have declared your data variable as an object.
You should use:
let data = [];
instead of
let data = {};
So it's going to look like this:
let data = [];
if (Page1.includes(val)) {
data.push("1");
}
etc...

Getting file name with second largest number in it when the numbers are same

I was trying to get file name in which is second largest number and it always outputs the file with largest number. What am I doing wrong?
Example: I have 3 file names in which are stored numbers like: 6 or 6 or 1 and it always outputs first file name with number 6 in it. I need to output the file name with second number 6.
const getSecondFileName = (pathToFolder) => {
const files = fs.readdirSync(pathToFolder);
const content = files.map(f => +fs.readFileSync(`${pathToFolder}/${f}`, 'UTF-8'));
const arrayCopy = [...content];
const secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]
const secondFileWithLargestInteger = files[content.indexOf(secondLargestNum)];
return secondFileWithLargestInteger;
}
Thank you for every answer.
since indexOf returns the first occurrence and you're firstLargestNum and secondLargestNum are the same (wich is a special case), let's handle it apart
const getSecondFileName = (pathToFolder) => {
let secondFileWithLargestInteger;
const files = fs.readdirSync(pathToFolder);
const arrLength = files.length;
const content = files.map(f => +fs.readFileSync(`${pathToFolder}/${f}`, 'UTF-8'));
const arrayCopy = [...content];
const sortedArray = arrayCopy.sort(function(a, b){
return a - b;
});;
const firstLargestNum = sortedArray[arrLength- 1];
const secondLargestNum = sortedArray[arrLength- 2];
if (firstLargestNum === secondLargestNum) {
const indexofFirst = content.indexOf(secondLargestNum);
// const indexofFirst = content.indexOf(firstLargestNum); same
secondFileWithLargestInteger = files[content.indexOf(secondLargestNum, (indexofFirst + 1))]
} else {
secondFileWithLargestInteger = files[content.indexOf(secondLargestNum)];
}
return secondFileWithLargestInteger;
}
I'm using a different method than yours here to sort, because element in your files are string.
var numbers = ['1', '5', '12', '3', '7', '15', '9'];
// Sorting the numbers array simply using the sort method
numbers.sort(); // Sorts numbers array
alert(numbers); // Outputs: 1,12,15,3,5,7,9
Sort method sorts the array elements alphabetically

Addition not working correctly in ExpressJs, Where subtraction is working correctly

I am doing a NodeJs Project. I am facing this problem.Subtraction is working correctly But addition is creating the problem.................
var previous_stock=results[0]['remain_stock']; //suppose value is 123
var products_qty=request.body.products_qty; //suppose valut is 7
var update_data={
remain_stock:previous_stock-products_qty, //output is 116
}
var update_data2={
remain_stock:previous_stock+products_qty, //output is 1237
}
How to solve that problem??
When used on a String, the + operator concatenates, even if the String only consists of digits. Assuming all your string values are base 10, wrap them in parseInt(string, 10). Note that you should also do this to products_qty if it's a String.
var previous_stock = results[0].remain_stock
var products_qty = request.body.products_qty
var update_data = {
remain_stock: parseInt(previous_stock, 10) - products_qty
}
var update_data2 = {
remain_stock: parseInt(previous_stock, 10) + products_qty
}

Convert Uint8Array into hex string equivalent in node.js

I am using node.js v4.5. Suppose I have this Uint8Array variable.
var uint8 = new Uint8Array(4);
uint8[0] = 0x1f;
uint8[1] = 0x2f;
uint8[2] = 0x3f;
uint8[3] = 0x4f;
This array can be of any length but let's assume the length is 4.
I would like to have a function that that converts uint8 into the hex string equivalent.
var hex_string = convertUint8_to_hexStr(uint8);
//hex_string becomes "1f2f3f4f"
You can use Buffer.from() and subsequently use toString('hex'):
let hex = Buffer.from(uint8).toString('hex');
Another solution:
Base function to convert int8 to hex:
// padd with leading 0 if <16
function i2hex(i) {
return ('0' + i.toString(16)).slice(-2);
}
reduce:
uint8.reduce(function(memo, i) {return memo + i2hex(i)}, '');
Or map and join:
Array.from(uint8).map(i2hex).join('');
Buffer.from has multiple overrides.
If it is called with your uint8 directly, it unnecessarily copies its content because it selects Buffer.from( <Buffer|Uint8Array> ) version.
You should call Buffer.from( arrayBuffer[, byteOffset[, length]] ) version which does not copy and just creates a view of the buffer.
let hex = Buffer.from(uint8.buffer,uint8.byteOffset,uint8.byteLength).toString('hex');
Buffer is nodeJS specific.
This is a version that works everywhere:
const uint8 = new Uint8Array(4);
uint8[0] = 0x1f;
uint8[1] = 0x2f;
uint8[2] = 0x3f;
uint8[3] = 0x4f;
function convertUint8_to_hexStr(uint8) {
Array.from(uint8)
.map((i) => i.toString(16).padStart(2, '0'))
.join('');
}
convertUint8_to_hexStr(uint8);

Resources