How to Convert from Hex to Ascii in JavaScript

How to convert from Hex to ASCII in JavaScript?

function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'

Javascript hexadecimal to ASCII with latin extended symbols

First an example solution:

let demoHex = `0053007400720069006E006700200068006100730020006C0065007400740065007200730020007700690074006800200064006900610063007200690074006900630073003A0020010D002C00200161002C00200159002C0020002E002E002E`;

function hexToString(hex) {
let str="";
for( var i = 0; i < hex.length; i +=4) {
str += String.fromCharCode( Number("0x" + hex.substr(i,4)));
}
return str;
}
console.log("Decoded string: %s", hexToString(demoHex) );

Convert array of hex to array to ASCII (Javascript)

First of all 4d is not a valid hex in javascript, you will need to append the 0x prefix to mark it as hex, then you can map over the array & execute String.fromCharCode

const name = [0x4d, 0x55, 0x48, 0x41, 0x4d, 0x4d, 0x41, 0x44, 0x20, 0x4e, 0x41, 0x5a, 0x52, 0x45, 0x45, 0x4e, 0x20, 0x42, 0x49, 0x20, 0x4e, 0x20, 0x5a, 0x41, 0x49, 0x4e, 0x55, 0x44, 0x49, 0x4e];
const result = name.map(hex => String.fromCharCode(hex));
console.log(result);

Hex to ascii wrong conversion

This happens because JavaScript and Node-RED use the UTF-8 encoding for text, where the Unicode character number U+009c is encoded as c2 9c. (Please note that ASCII is actually a 7-bit character set from 0x00 to 0x7f, and the 8-bit codes from 0x80 to 0xff depend on the charset or encoding.)

Node-RED has also binary support (see this GitHub issue). The documentation is rather vague, but looks like you should use a Node.js Buffer object as the payload.

convert Hexadecimal to text (ASCII) or JSON object in Node.js (Javascript)

You should firstly remove spaces from your HEX string:

str = str.replace(/\s/g, '');

After that you can use your function.

Javascript: Hex to String without converting to ascii, int or xyz

You can convert the hexadecimal values to string by using toString(16). For more read the MDN Doc.

const arr = [0x69, 0x72, 0x33, 0x88];
const base16string = arr.map(item => item.toString(16));

console.log(base16string);
.as-console-wrapper {min-height: 100%!important; top: 0}


Related Topics



Leave a reply



Submit