Thread: string to hexadecimal

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    4

    string to hexadecimal

    i need to convert a string to hexadecimal as follows :

    String : "12345678"
    needs to be converted to a
    Code:
     char value[4] = { '0x12' ,'0x34' , '0x56' , '0x78'};
    How Can that be done ?

    Thx

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    It appears you just did it

    Look up sscanf() format specifiers. %2x 4 times in the format string will do it.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    4
    Thx for the reply ,
    Actually i just wanted to show how i wanted the result to be. the actual string would be of variable length.so i need a function to transform the string characters to hexadecimal the way showed above.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    As I said above, you can use sscanf() with an appropriate format string. In C++, a more idiomatic way would be to use string streams.

    I'll leave it as an exercise to work out how to turn a hex digit (in the range '0' to '9' or the range 'A' to 'F') to a numeric value (0x0 to 0x9 or 0xA to 0xF).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. hexadecimal and character string usage?
    By vlrk in forum C Programming
    Replies: 3
    Last Post: 01-03-2012, 11:08 PM
  2. Hexadecimal value
    By MasterAchilles in forum C Programming
    Replies: 5
    Last Post: 11-19-2008, 07:12 AM
  3. convert string to hexadecimal
    By nocturna_gr in forum C Programming
    Replies: 3
    Last Post: 12-11-2007, 04:45 AM
  4. Hexadecimal
    By Driveway in forum C++ Programming
    Replies: 12
    Last Post: 06-26-2002, 03:26 PM
  5. hexadecimal
    By pierremk in forum C++ Programming
    Replies: 2
    Last Post: 03-12-2002, 08:05 PM