Node - Convert from base64 string to utf-8 byte code array - node.js

I'm currently trying to convert images from a base 64 string to a utf-8 byte code array. Below is the code I'm attempting to use with the base 64 string replaced for clarity. I'm getting what looks to be a utf-8 byte array, but have not been able to find a way to verify. Any help with a resource to help verify or if the code is incorrect?
const b64 = '...base64 string';
// convert to utf8 string
const utf8 = (Buffer.from(b64, 'base64')).toString('utf8');
// create a buffer of utf8 string
const buff = Buffer.from(utf8, 'utf8');
//
const arr = [...buff];

Related

NodeJS parseInt() function does not return correct HEX value

I have the following code to convert a binary to a hex in NodeJS:
const bin = "1011100100001011101010100011100100001001101000100011101110110101101111011000001111111100010010111110001110101011100111101101110101100110110111000001111010101010110001110001110000110101001111111101000100110011111000010111110011001011000000001001010000100100"
const hex = parseInt(bin, 2).toString(16).toUpperCase();
console.log(hex)
and it only return:
B90BAA3909A23800000000000000000000000000000000000000000000000000
As maximum safe integer in JavaScript is just 2^53 - 1 or 0b11111111111111111111111111111111111111111111111111111 (see Number.MAX_SAFE_INTEGER), you need BigInt here:
const bigIntFromBin = BigInt("0b1011100100001011101010100011100100001001101000100011101110110101101111011000001111111100010010111110001110101011100111101101110101100110110111000001111010101010110001110001110000110101001111111101000100110011111000010111110011001011000000001001010000100100");
const bigIntHex = bigIntFromBin.toString(16).toUpperCase();
console.log(bigIntHex);

Writing bytes in a pdf

I am getting a response for an API in form of bytes.
let a = "JSHDHHFHFHHFKFLLFLDMDMDMDMMSKKW==";
I want to write this into a pdf file.
The approach I have taken till now is to convert it to binary using atob library. Then I convert it to a Uint8Array and write to a file using fs.writestream. When the file write completes it gives me an output of unidetified type.
%
1 0 obj
<</Filter/FlateDecode/First 141/N 20/Length 848/Type/ObjStm>>
stream
xUmoâ8þ+óm[U½ø%/ÎiU ÈÂr]º¸ë¢|ð/)`©ý÷7ã´vK·HQ2gÆÏ3À#)ÀcHBd#*P§¤ Î U8GC8q3È_C¦x¦¤øU8Oà3$c¨*Æ/æK?óÝ7÷¸5Á`
íÆ-Ð4?¶Î¬Çï²3Ù=0YØÑ8èm0.ÍÆUî1  ¢ý+3í²©¶Î6"ûº5~º?½»®Fzçôºº¹!ÙO>=¸ÑÜigºù÷¼ÏyDqÇIè?*Ê¥J!âB)ÿ§ ½àøÌÝDÇþ{;ü2¹ê5®¯û¶.'1Í«ÚÊZã#$~4GØÿda0vº®½Íª6H-­àZ&Lo?jõÃáÁIÐ림=¬õªñ+¿T¿oòë³S$±Þ±ð³wzm^ú²ÍNϨJ[Bß6iEði³´eµYíi»þ|#ÜÂþ½©ÐÁx/iãt©ÑÕÌT¯LKNy³µ]½dzHÞÈì¿ì¯Á¢ùï2Ta°<b¬HDNµ¤¹êþø2Äz=WTâ÷hg õr¡æQîI²2xj;÷æÁe[|Ó à±¦#b\:IEÌ,ékvª_]ØÌ´v×,Mû$êCô¯hêgþp»DEäÁ4óàµ#Å¡v$§vDx¤y yR;qè#Q;ByÇíÓ{Z6»£UÛªlsλ
ÜÙ>5»[pÍÎ_§tíO;Û¬u}¢ñm·µYv|mJÓ`)_<×Ç%²½ªZ×<^ôJûÍ\þÒ{£Þð'"u?ÅÅ!\{þÈ~?âEF¡xàBxÏþigX]¿quu&^/ú¶ìŽIüþvZj<§A_½ñ¾ëº5¯ÖÄ.²?ãsÁY_1ñ±Á 1ÚUvó¶
£Ü-Ms1~ÑÛº#Hÿìr$ö¤ÿ²}R
endstream
endobj
22 0 obj```
When I am trying the response on online editor it gives me the write response.
The code I have used till now.
let encodedPDF = JSON.parse(d).Resp_Policy_Document.PDF_BYTES;
var bin = atob(encodedPDF);
var binaryLen = bin.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++)
{
var ascii = bin.charCodeAt(i);
bytes[i] = ascii;
}
let writer=fs.createWriteStream('Last.pdf');
writer.write(bin);
The data you get is Base64 encoded. That's a pretty common way for APIs to pass information. The giveaways? the equal signs at the end, and the use of ASCII uppercase and lowercase letters, numbers, +, and /.
So, you need to decode it that way. Use something like this
const pdfBinary = Buffer.from(a, 'base64');
The contents of this buffer, I guess, are a pdf document. You should write it directly to a file without trying to convert it to a text string.

How to get the right values when I convert hex to ascii character

I'm trying to convert a hexa file to text, using javascript node js.
function hex_to_ascii(str1){
var hex = str1.toString();
var str = '';
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return str;
}
I have a problem concening the extended ASCII charaters, so for example when I try to convert 93 I've get “ instead of ô and when I convert FF I've get ÿ instead of (nbsp) space.
I want to get the same extended charaters as this table: https://www.rapidtables.com/code/text/ascii-table.html
This problem is slightly more complex than it seems at first, since you need to specify an encoding when converting from extended ascii to a string. For example Windows-1252, ISO-8859-1 etc. Since you wish to use the linked table, I'm assuming you wish to use CP437 encoding.
To convert a buffer to string you need a module that will do this for you, converting from a buffer (in a given encoding) to string is not trivial unless the buffer is in a natively supported node.js encoding, e.g. UTF-8, ASCII (7-bit only!), Latin1 etc.
I would suggest using the iconv-lite package, this will convert many types of encoding. Once this is installed the code should look as follows (this takes each character from 0x00 to 0xFF and prints the encoded character):
const iconv = require('iconv-lite');
function hex_to_ascii(hexData, encoding) {
const buffer = Buffer.from(hexData, "hex");
return iconv.decode(buffer, encoding);
}
const testInputs = [...Array(256).keys()];
const encoding = "CP437";
console.log("Decimal\tHex\tCharacter")
for(let input of testInputs) {
console.log([input, input.toString(16), hex_to_ascii(input.toString(16), encoding)].join("\t"));
}

node.js buffer toString default utf8 but i want no encoding

var iconv = require('iconv').Iconv;
var UtfToEuckr = new iconv('utf-8', 'euckr');
var result = UtfToEuckr.convert('한글');
var str = result.toString(); <- default convert utf8
str is UTF-8 string
i wanna no encoding to string
want result : str is euckr string
please, tell me know how..
thank for reading
you always have some encoding, you should either try "ascii" or "binary" (whichever you mean in your situation)

Decoding and encoding in Base64 in java

I am getting a Base64 decoded String from out side network, i ll convert the string to byte and decode it. then it will change to ASCII format. I ll store this ASCII in string send to another server.
In this case when i again encode the ASCII i am not getting the same value what i have received from out side network. But it works fine in unix system, problem is only in windows.
// Base64 Encode
String orig = "mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3I24peAUBHdli8GP/MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCp0XSZCe1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0kBfHv4WMQwz1dQ+MommXmA==";
byte [] decodedvalue = Base64.decodeBase64(orig.getBytes());
byte [] encodedvalue = Base64.encodeBase64(decodedvalue);
System.out.println("ORIGINAL VALUE : "+orig);
System.out.println("ENCODED VALUE : "+new String(encodedvalue));
String aa =new String(decodedvalue);
String temp = new String(Base64.encodeBase64(aa.getBytes()));
System.out.println(" String encoded value : " +temp);
ORIGINAL VALUE : mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3I24peAUBHdli8GP/MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCp0XSZCe1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0kBfHv4WMQwz1dQ+MommXmA==
ENCODED VALUE : mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3I24peAUBHdli8GP/MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCp0XSZCe1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0kBfHv4WMQwz1dQ+MommXmA==
String encoded value : mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3D+4peAUBHdli8E//MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCj8XST+e1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0PxfHv4WMQwz1dQ+MommXmA==

Resources