Results 1 to 12 of 12

Thread: Convert Character String to Hex using C

  1. #1

    Thread Starter
    New Member
    Join Date
    Oct 2002
    Location
    Ames, IA
    Posts
    8

    Convert Character String to Hex using C

    I'm probably just not thinking tonight because _a_ solution to this is on the tip of my fingers but I can't make it happen. Please keep in mind, I'm sticking mostly to C conventions, trying to include as little C++ as possible (for the sake of some requirements I put on myself early on in the project proposal).

    What I'm trying to do is take a string in from a user (scanf()) and convert that string to Hex. I think I need to look at each character sequentially, find the ASCII value for that character, and then convert that ASCII value to hex. As part of my final requirements, I will need to be able to convert to and from Binary as well. Is there a good way to do this in C?

    Here's an example:

    User Enters: abc
    In Binary: 01100001 01100010 01100011
    In Hex: 61 62 63

    Background: For those that care, I'm implementing SHA-1 very crudely. For my Information Systems Security class, I'm comparing speed differences between an implementation in VB and C. The user will simply be allowed to enter a phrase or some text at a prompt and the application will find the hash for that section. The information I am following for the implementation is from NIST (National Institute of Standards and Technology). The document is FIPS PUB 180-1.

  2. #2
    Addicted Member HairyDave's Avatar
    Join Date
    Aug 2002
    Location
    Er...I can't remember.
    Posts
    196
    Do you need to do anything to the value after its converted?

    If you only want to print it out you can just use printf with a %h field. This is explained in the example for printf, wprintf in the MSDN library.

    If you want to do anything with the hex, you could store its hex representation in a string perhaps using sprintf.

    Any help?

    HD

  3. #3
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  4. #4

    Thread Starter
    New Member
    Join Date
    Oct 2002
    Location
    Ames, IA
    Posts
    8
    HairyDave - Could you elaborate on what I could do with sprintf()? It's been about two years since I've used C at all so I'm quite rusty. I do need to use the value when once I have it.

    kedaman - I need to go from a string to a hex value, not from an integer value to a string. Based on your suggestion, I looked into atol() but that didn't seem to do what I wanted either. When I run that function with an input string of "abc" it returns 0. I'm assuming that means there was an error somewhere, but I cannot pinpoint where.

    Any other ideas?

  5. #5
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    in your string "abc"
    the first char should be 61, the next 62, the third 63, try for instance
    #include <stdio.h>
    #include <stdlib.h>

    int main ()
    {
    char* x="abc";
    char buffer [10];
    itoa(x[0],buffer,16);
    printf ("%s\n",buffer);
    }
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  6. #6

    Thread Starter
    New Member
    Join Date
    Oct 2002
    Location
    Ames, IA
    Posts
    8
    That code will translate my first character, but what would I need to do to convert the entire string to a hexadecimal number? I just don't think I understand what you are getting at with the idea.

    Pseudo Code:
    Get String from user
    Convert String to Hex
    Manipulate String

  7. #7
    Addicted Member HairyDave's Avatar
    Join Date
    Aug 2002
    Location
    Er...I can't remember.
    Posts
    196
    sprintf just prints the value to a string.

    Kedaman actually means atoi (string to int).

    Looking at your original example, you're not using hex anyway. Your "abc" example gives 61 62 63 as hex - these are just ASCII values.

    If you do want hex and you want to manipulate the hex after, you can:

    1. Convert string to integer (itoa)
    2. If you can convert to hex using the base variable then great - otherwise you could print the integer to a string using sprintf. sprintf works just like printf but with an output buffer (see MSDN).
    3. Hex representation is stored in the string so you can use it.

    Any help?

    HD

  8. #8
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    i meant itoa, int to string, if you want them sequentially appended to the string (you can do this for bases that are powers of 16, 256 the ascii code base is 16 to the power of 2) just shift the buffer and use itoa again.

    int main ()
    {
    char* x="abc";
    char buffer [10];
    char* b=buffer;
    while(*x)itoa(*(x++),b++++,16);
    printf ("%s\n",buffer);
    }

    this time x traverses the string in the loop which uses itoa on each ascii char in the string til null terminates it. Meanwhile a buffer pointer traverses the buffer so that it appears as if the hex values are appended in the buffer.
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  9. #9
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    If kedaman says he means something one way, then you stand a very good chance that he actually does!
    But: b++++
    As per the definition of postfix ++ this won't work. It resolves to
    (b++)++
    where b++ increments b, then returns the old value, which then is incremented again. In effect you increment b only once.

    Schpider, what do you want to do with the hex values once you have them?
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  10. #10
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Btw, itoa is a non-standard MS extension.
    The standard method is sprintf.

    Code:
    void printhexes(const char *str)
    {
      const char *p;
      for(p=str;*p;++p)
        printf("%02x ", (const int)*p);
    }
    
    // or...
    void gethexes(char *buf, const char *str)
    {
      const char *p;
      char *b = buf;
      for(p=str; *p; ++p)
        b += sprintf(b, "%02x ", (const int)*p);
      *b = 0;
    }
    And finally, here's a function that converts an integer to it's binary string representation.
    Code:
    char * itobs(int in, int min_prec, char *buf)
    {
      char *b = buf;
      int bits = 32;
      while(bits > min_prec  && in & 0x80000000 == 0) {
        in <<= 1; --bits;
      }
      while(bits > 0) {
        *b++ = '0' + ((in & 0x80000000) >> 31);
        in <<= 1; --bits;
      }
      *b = 0;
      return buf;
    }
    min_prec is the minimum precision, if there are fewer significant digits it will be padded with zeroes.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  11. #11
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    Originally posted by CornedBee
    (b++)++
    a slight modification was typing while i was sleeping

    char* b=buffer-2;
    while(*x)itoa(*(x++),++++b,16);
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  12. #12
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    b+=2
    is one character shorter and easier to read.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width