Javascript: Convert a hexadecimal encoded String to a hexadecimal byte - javascript

Now I have to convert the hexadecimal encoded in a String to a byte hexadecimal.
var str = "5e"
var b = // Should be 0x5e then.
if str = "6b", then b = 0x6b and so on.
Is there any function in javascript, like in java
Byte.parseByte(str, 16)
Thanks in advance

The function you want is parseInt
parseInt("6b", 16) // returns 107
The first argument to parseInt is a string representation of the number and the second argument is the base. Use 10 for decimal and 16 for hexadecimal.

From your comment, if you expect "an output of 0x6b" from the string "6b" then just prepend "0x" to your string, and further manipulate as you need. There is no Javascript type that will output a hexadecimal in a readable format that you'll see prefixed with '0x' other than a string.

I solved it by using just
new Buffer("32476832", 'hex')
this solved my problem and gave me the desired buffer
<Buffer 32 47 68 32>

Related

What is this type of string called?

In python, we can do something like print("some random string".encode().decode('utf-16')) which will output: 潳敭爠湡潤瑳楲杮.
I feel like that is utf-16, but I'm not really sure, because I can't reproduce it in any other language. My goal is to create a function that will do exactly this, but in Javascript. The problem is that I can't find what of what type if this type of string...
Does someone know how this is called or/and how I could reproduce this in JS ?
A string is a sequence of runes. Unicode is a standard for assigning numeric values to those runes. UTF-8 or UTF-16 are standards for encoding a sequence of runes, as represented by their unicode numeric values, as a sequence of bytes.
What you did there is use encode with the default encoding, which is UTF-8, to get a sequence of bytes which you then tried to decode back to runes as if the bytes had come from a UTF-16 encoding. Basically (because your input string fits in a 1-byte encoding for UTF-8) you're taking pairs of characters from the input, jamming their bytes together and hoping that the resulting value is a legal UTF-16 encoding of something (which in general you cannot count on being true). You'll also run into issues if the utf-8 encoding is not an even number of bytes, of course.
If you really need to do this thing in javascript, you could do something like this:
const str = "some random string";
var buf = new ArrayBuffer(str.length);
// Reinterpret the sequence of bytes as a sequence of byte pairs.
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i < strLen-1; i+=2) {
var c1 = str.charCodeAt(i);
var c2 = str.charCodeAt(i+1);
if (c1 > 127 || c2 > 127) {
// This will be a problem. How you handle it is up to you.
}
bufView[i/2] = c1 << 8 | c2;
}
console.log(String.fromCharCode.apply(String, bufView));

JS base n string to base64

I have a string (with numbers under 128) separated by a comma:
"127,25,34,52,46,2,34,4,6,1"
Because there are 10 digits and one comma, that makes 11 total characters. How can I convert this string from "base 11" to "base 64"? I would like to compress this string into base64. I tried window.btoa, but it produces a larger output because the browser doesn't know that the string only has 11 characters.
Thanks in advance.
Base64 encoding never produces shorter strings. It is not intended as a compression tool, but as a means to reduce the used character set to 64 readable characters, taking into account that the input may use a larger characterset (even if not all those characters are used).
Given the format of your string, why not take those numbers and use them as ASCII, and then apply Base64 encoding on that?
Demo:
let s = "127,25,34,52,46,2,34,4,6,1";
console.log(s);
let encoded = btoa(String.fromCharCode(...s.match(/\d+/g)));
console.log(encoded);
let decoded = Array.from(atob(encoded), c => c.charCodeAt()).join();
console.log(decoded);

String of Binary to Buffer in Node.js

I'm trying to convert a string of 0 and 1 into the equivalent Buffer by parsing the character stream as a UTF-16 encoding.
For example:
var binary = "01010101010101000100010"
The result of that would be the following Buffer
<Buffer 55 54>
Please note Buffer.from(string, "binary") is not valid as it creates a buffer where each individual 0 or 1 is parsed as it's own Latin One-Byte encoded string. From the Node.js documentation:
'latin1': A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC 1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes).
'binary': Alias for 'latin1'.
Use "".match to find all the groups of 16 bits.
Convert the binary string to number using parseInt
Create an Uint16Array and convert it to a Buffer
Tested on node 10.x
function binaryStringToBuffer(string) {
const groups = string.match(/[01]{16}/g);
const numbers = groups.map(binary => parseInt(binary, 2))
return Buffer.from(new Uint16Array(numbers).buffer);
}
console.log(binaryStringToBuffer("01010101010101000100010"))

When I try to convert a hex string to an integer in JavaScript, I don't get the same number as I do in python

I've been trying to convert a hex string to an integer in JavaScript but the number I get isn't the same as the number I get in python.
Here's my code in JS:
var x = CryptoJS.MD5('h').toString();
BigInt(parseInt(x, 16));
Here's what I get:
49268479078006859472353325704298889216n
And when I run this in python:
int(hashlib.md5('h'.encode()).hexdigest(), 16)
I get:
49268479078006861543109070154241760913
parseInt has already lost the precision for you by converting to a number before you convert to BigInt.
You can use… a 0x prefix? It seems weird, like there’s a missing BigInt.parse API, but there you go.
BigInt('0x' + x)

How do I convert string hex representation to byte ? - javascript

My problem consists of stream of bytes or array of bytes.
This is no problem with these
'\u0000'
'\u0000'
'\u0001'
'\u0010'
But the problem lies when i decode some special characters as this
'\u0000'
'\u0000'
'\u0000'
'�'
from right to left(or here bottom to top) i can get the numeric value of these 4 bytes to 1 integer or number. but I dont know if this is correct
toInt (buff){
console.log('buff ' , typeof buff[0]);
for(let b of buff){
console.log('b' , b);
}
return (buff[3] & 0x000000ff ) |
(buff[2] & 0x0000ff00 ) << 8 |
(buff[1] & 0x00ff0000 ) << 16 |
(buff[0] & 0xff000000 ) << 24 ;
}
I'm not sure I've understood your question correctly but sounds like you want to convert an array of strings which represent hex bytes into a number.
If you've got a string representation of hex numbers you could convert them using something like:
function bufferToInt(buff) {
var string = buff.join('');
return parseInt(string, 16); // parseInt allows specifying a base
}
bufferToInput(['ff', 'ff']); // This returns 65535
Assuming each element in buff contained a string representation of a hex byte such as "ff" the above should allow simple conversion to an number using mainly built in functions.

Categories

Resources