0

I want to convert this array of hex to array of ASCII.

I have tried to convert the array to string and using a function to convert hex string into ASCII, does not meet my expectation.

var name = [4d,55,48,41,4d,4d,41,44,20,4e,41,5a,52,45,45,4e,20,42,49,,4e,20,5a,41,49,4e,55,44,49,4e];

name=hex2str(name);

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

  

Expecting output:

name = [M,U,H,A,M,M,A,D, ,N,A,Z,R,E,E,N, ,B,I,N, ,Z,A,I,N,U,D,I,N]
1
  • This looks like PHP not JavaScript. Commented Jun 18, 2019 at 7:17

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.