ascii to hex

This is a discussion on ascii to hex within the C++ Programming forums, part of the General Programming Boards category; Hi everybody, I have a single char which I want to look up the hexadecimal value for. I couldn't find ...

  1. #1
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343

    ascii to hex

    Hi everybody,

    I have a single char which I want to look up the hexadecimal value for. I couldn't find a plain ascii_to_hex function so my question is simple.. is there a function somewhere in the headerfiles or do I have to code my own?

    example:

    i have a single 'A' and want to get the hex value for 'A' -> (41)


    Regards
    -David-

  2. #2
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343

    solved.

    I managed to solve the problem and here is what I came up with...

    Code:
    unsigned long getHexValue(char ch)
    {
      unsigned long ret = 0x0;
    
      /* mask the first 4 bits and shift 4 bits right */
      ret = ((ch & 0xF0) >> 4);
    
      /* shift 4 bits left */
      ret = (ret << 4);
    
      /* append the last 4 bits */
      ret |= (ch & 0x0F);
      
      return ret;
    }
    If there is someone with a better solution just let me know.

    Regards
    -David-

  3. #3
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493
    as far as i understand (which isn't that far) hex numbers == decimal numbers
    an ascii char is a value. you need to put it in a string or something. to print it in hex you could do this:
    Code:
    unsigned char value = 56; // any value < 256 will do
    char let1,let2;
    let1 = value / 16;
    let2 = value % 16;
    if (let1 > 9) let+='A' - 10;
    else let+='0';
    if (let2 > 9) let+='A' - 10;
    else let+='0';
    cout << let1 << let2;
    i'll bet that printf has a way of printing hex without this. i'll almost positive of it. and cout probably can, too.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    How about?

    cout << hex << (int)'A' << endl;

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Or?

    char hex[10];
    sprintf(hex,"%X",'A');
    cout << hex << endl;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Char to ASCII Hex Value Troubles
    By MattMik in forum C++ Programming
    Replies: 6
    Last Post: 03-25-2008, 02:17 PM
  2. Ascii to hex and hex to Ascii
    By beon in forum C Programming
    Replies: 1
    Last Post: 12-26-2006, 05:37 AM
  3. Replies: 11
    Last Post: 03-24-2006, 10:26 AM
  4. Encrypting text file with ASCII hex
    By supaben34 in forum C++ Programming
    Replies: 1
    Last Post: 03-24-2005, 05:35 PM
  5. Hex to Ascii conversion
    By Ryno in forum C Programming
    Replies: 2
    Last Post: 03-24-2005, 08:16 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21