4

In C, I'd be able to do something like this:

short number = 20693; // Create the number
unsigned char* str = malloc(3); // Create the string
memcpy(str, &number, 2); // Copy the number to the string
str[2] = 0; // 0-pad it

And then str would contain the utf-8 representation of number. Is it possible to do this in javascript (without the 0-padding)?

MiJyn
  • 5,327
  • 4
  • 37
  • 64
  • 2
    Possible dup: http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript – tymeJV Jun 12 '13 at 18:28
  • Obviously it's possible, but your C example is **hilariously** irrelevant to a JavaScript solution. – user229044 Jun 12 '13 at 18:29
  • @tymeJV, nope, that one wants to convert a number into a binary number (like 25 would become 11001), and I want the number to be, well, encoded in binary (like 65 would become "A") – MiJyn Jun 12 '13 at 18:29
  • @MiJyn Err, maybe take out the reference to "binary" then. You're looking for the ASCII number for a given character, this has **nothing** to do with binary. – user229044 Jun 12 '13 at 18:31
  • @meagar, okay, but a quick note: it's not the ASCII number, it would be the UTF-8 number (which is what the C example does) – MiJyn Jun 12 '13 at 18:31
  • 2
    I don't believe this is a duplicate. they are two completely different questions. Which the answers are both different as you can see. – mjwrazor May 09 '17 at 19:49
  • I'm voting to re-open. The question is not a duplicate, and the accepted answer is not correct - fromCharCode accepts UTF-16, not UTF-8. It's a shame to be googling the answer years after this was asked, and be blocked/delayed by a fake duplicate claim. – JSideris Apr 21 '20 at 23:54

1 Answers1

13

You want String.fromCharCode...

String.fromCharCode(65);  // "A"

...which is the opposite of String.charCodeAt:

"A".charCodeAt(0); // 65
user229044
  • 232,980
  • 40
  • 330
  • 338