How to convert hex numbers to byte string? - javascript

> str = '\xae\xee'
'®î'
How to convert [0xae, 0xee] to '®î'?

You can use String.fromCharCode() to convert the hex values to their string representation with .map() and .join() to form a string:
const hex = [0xae, 0xee];
const res = hex.map(s => String.fromCharCode(s)).join('');
console.log(res);

Related

How to convert a bit string to base64 in node.js?

I have a bit string that I want to convert to base64 but it doesn't look like there's a native function to do this and I couldn't find a node module either. ):
Input: 100110110101000110100011011001100010110100011011001100100110100011000001100000110000011000001100001001010100111110000011001111100101010011111010011100010110001001001001100000110100111010010100111110000111001000100000110001001000101100111110011001001001101011010001011001001101001010000011000100100100110000011010011
Output: base64 representation of that equivalent binary value
Maybe a better question is how to convert a bit string into a buffer? Not sure
As you guessed, the main thing is converting the string into something easier to convert to base64 and then converting that to base64.
In the code below, we do these conversion sequences:
bit string -> BigInt -> array of byte-sized ints -> binary string -> base64
base64 -> binary string -> array of byte-sized bit strings -> bit string
const encode = bitstr => {
const bytes = [];
// convert bit string to BigInt
let value = BigInt('0b' + bitstr);
// chop it up into bytes
while (value > 0n) {
bytes.unshift(Number(value & 0xffn));
value >>= 8n;
}
// convert to binary string and encode as base64
return btoa(String.fromCharCode.apply(null, bytes));
};
const decode = b64 => {
// decode base64 to binary string
const bstr = atob(b64);
// convert binary string to bit string
return new Array(bstr.length).fill(0).map(
(_,i) => bstr.charCodeAt(i).toString(2).padStart(8, i ? '0' : '')
).join('');
};
const bitstr = '100110110101000110100011011001100010110100011011001100100110100011000001100000110000011000001100001001010100111110000011001111100101010011111010011100010110001001001001100000110100111010010100111110000111001000100000110001001000101100111110011001001001101011010001011001001101001010000011000100100100110000011010011';
const encoded = encode(bitstr);
const decoded = decode(encoded);
console.log(bitstr);
console.log(encoded);
console.log(decoded);

Convert dot notation string to array notation string with JavaScript

Let's say I have a dot notation string.
let str = 'category.1.subcategory.2.name';
Are there any suggestions on how to convert it to an array notation string?
convert(str); //desired outcome => 'category[1][subcategory][2][name]'
let str = 'category.1.subcategory.2.name'
var parts = str.split(".")
var stra = parts[0] + parts.slice(1).map(p => `[${p}]`).join("")
console.log(stra)

Encode String to HEX

i have my function to convert string to hex:
function encode(str){
str = encodeURIComponent(str).split('%').join('');
return str.toLowerCase();
}
example:
守护村子
alert(encode('守护村子'));
the output would be:
e5ae88e68aa4e69d91e5ad90
It works on Chinese characters. But when i do it with English letters
alert(encode('Hello World'));
it outputs:
hello20world
I have tried this for converting string to hex:
function String2Hex(tmp) {
var str = '';
for(var i = 0; i < tmp.length; i++) {
str += tmp[i].charCodeAt(0).toString(16);
}
return str;
}
then tried it on the Chinese characters above, but it outputs the UTF-8 HEX:
5b8862a467515b50
not the ANSI Hex:
e5ae88e68aa4e69d91e5ad90
I also have searched converting UFT8 to ANSI but no luck.
Anyone could help me? Thanks!
As a self-contained solution in functional style, you can encode with:
plain.split("")
.map(c => c.charCodeAt(0).toString(16).padStart(2, "0"))
.join("");
The split on an empty string produces an array with one character (or rather, one UTF-16 codepoint) in each element. Then we can map each to a HEX string of the character code.
Then to decode:
hex.split(/(\w\w)/g)
.filter(p => !!p)
.map(c => String.fromCharCode(parseInt(c, 16)))
.join("")
This time the regex passed to split captures groups of two characters, but this form of split will intersperse them with empty strings (the stuff "between" the captured groups, which is nothing!). So filter is used to remove the empty strings. Then map decodes each character.
On Node.js, you can do:
const myString = "This is my string to be encoded/decoded";
const encoded = Buffer.from(myString).toString('hex'); // encoded == 54686973206973206d7920737472696e6720746f20626520656e636f6465642f6465636f646564
const decoded = Buffer.from(encoded, 'hex').toString(); // decoded == "This is my string to be encoded/decoded"
I solved it by downloading utf8.js
https://github.com/mathiasbynens/utf8.js
then using the String2Hex function from above:
alert(String2Hex(utf8.encode('守护村子')));
It gives me the output I want:
e5ae88e68aa4e69d91e5ad90
This should work.
var str="some random string";
var result = "";
for (i=0; i<str.length; i++) {
hex = str.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
If you want to properly handle UTF8 strings you can try these:
function utf8ToHex(str) {
return Array.from(str).map(c =>
c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) :
encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
).join('');
},
function hexToUtf8: function(hex) {
return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
}
Demo: https://jsfiddle.net/lyquix/k2tjbrvq/
Another way to do it
function toHex(txt){
const encoder = new TextEncoder();
return Array
.from(encoder.encode(txt))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
}

convert Ascii into Hex in Java Script for comparison

I have an Ascii value (something like "#") that I want to convert into an hex in JavaSkript that I can compare this value with some other hex-values.
Are there any casting possiblities?
Best regards and thanks,
Florian
Convert Ascii strings into base64 (hex)
var b64 = btoa("##%##!##$%");
Convert base64 to Ascii:
atob(b64);
Don't know what you want to compare, beside equality.
// Convert a (UTF-8 or ASCII) string to HEX:
function stringToHex(string) {
return '0x'+[...string].map(char => char.codePointAt(0).toString(16)).join('')
}
// Convert a HEX string into a number:
function hexToNumber(hex) {
return parseInt(hex, 16)
}

javascript Convert string representation of hex value to hex

In Javascript, how do I convert a string representation of a hex value into it's hex representation ?
What I have returning from a checksum routine is a string value "FE". What I need is it's hex representation "\xFE"
I cannot simply do this, as it gives me an error:
var crc = "FE";
var hex = "\x" + crc;
This just gives me a new 4 character ASCII string:
var crc = "FE";
var hex = "0x" + "FE";
thxs for any guidance.
like this
var hex = parseInt("FF", 16);
For the string \xFE, escape the backslash: var hex = '\\x'+'FE'
To convert 'FE' to a Number use +('0xFE')
To show +('0xFE') as a hexadecimal, use (224).toString(16), or '0x'+((254).toString(16))

Categories

Resources