Convert long into ASCII Char[]

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jcan
    New Member
    • Oct 2008
    • 3

    Convert long into ASCII Char[]

    hi

    I have a long variable:

    long id = 0x0457;

    which in decimal is 1111

    I need to convert id into a char array with its ascii values.

    e.g

    char arr[4];

    arr[0] = '1';
    arr[1] = '1';
    arr[2] = '1';
    arr[3] = '1';

    thanks
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Try sprintf, or itoa although the latter function (itoa) while support by several compilers is actually non-standard and I would say may well suffer from re-entrancy issues since it returns a char * to a presumably static buffer.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Use a common algorithm.

      This 1111 is really

      1 *1000 + 1 * 100 + 1 * 10 +1.

      To see how many 100's there are you

      1111/100

      That gives the number of 100's. Now to get the digit in the 100's position you:

      (1111/100) %10

      Now you have a value between 0 and 9. It is an integer value. For a string you have to convert this to an ASCII char.

      (1111/100) %10 +'0'


      So, constuct a loop so you divide by 1000 then by 100 then by 10 etc and append the result to your string. When your divisor is 0, you are done.

      Comment

      Working...