Thread: convert string to hexadecimal

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    19

    convert string to hexadecimal

    Hi,
    i am using the following code, in order to convert a char array (or string) to its hexadecimal representation:
    Code:
    	byte hexval=0x00;
    	cout << "sscanf: ";
    	char car2[2];
    	car2[0]='1';
    	car2[1]='9';
    	sscanf( car2, "0x%02X", &hexval );	
    	printf("0x%02X", hexval);
    However, i get back the "0x00" value. With other "experiments" i didn't also manage to get the "0x13" back.

    Ideas?
    Thanks

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Your string has to look like the format: "0x%02X". So the first character needs to be '0', the second character needs to be 'x', the third and fourth are hex digits, and the fifth should be '\0'. Currently, you're not matching anything (sscanf returns 0 for no matches).

    (Also, you should decide whether this is C or C++.)

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    19
    Quote Originally Posted by tabstop View Post
    Your string has to look like the format: "0x%02X". So the first character needs to be '0', the second character needs to be 'x', the third and fourth are hex digits, and the fifth should be '\0'. Currently, you're not matching anything (sscanf returns 0 for no matches).

    (Also, you should decide whether this is C or C++.)
    char 1:0
    char 2:x
    char 3: ?
    char 4: ?
    char 5: \0

    What do you mean by hex digits? "x" or "X" is the representation for hex digits and the result of what you describe doesn't match the "0x%02X" you mention above- which is what i've already used.

    Can you be more specific? I am confused...
    Thanks

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    19
    I understand what you mean now... sorry, i am not a native speaker and i understood sth else

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  2. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM