Thread: hex and binary functions

  1. #1
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127

    hex and binary functions

    I am trying to make two functions. It should be pretty simple to make. It will take a character and return its hex value. Here is what I have but it doesn't seem to work.
    Code:
    char tohex(char a){
         char b;
         sprintf(b,"0x%x",a);
         return b;
    }
    What am I doing wrong?
    ~Sven

    EDIT-I did need to make the same thing for binary (hence the title) but I figured that one out.

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    You expect that character to hold that string? sprintf's first argument is a char * not a char.
    Last edited by SlyMaelstrom; 02-24-2006 at 06:44 PM.
    Sent from my iPadŽ

  3. #3
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    Well, first off like Sly said you can't write to a single character, you need to write to a character array.
    Secondly you shouldn't return an address to a local variable either so I'd do it like this:
    Code:
    #include <stdio.h>
    
    char* tohex (char* b, char a)
    {
         sprintf(b, "0x%0x", a);
         return b;
    }
    
    int main ()
    {
        char buf[5];
        char chr;
    
        puts(tohex(buf, chr));
    
        return 0;
    }
    The hex value of a char or 8-bit integer peaks at 2 characters so it's safe to allocate 5 chars for the whole thing.
    Also you could use better names for your variables, instead of a and b you could use num and buf respectively.
    Notice that you're passing and returning a char pointer and not a char. A char pointer usually means a zero-terminated string.

  4. #4
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127
    This is the best I could do because I wanted to do it myself. Why won't it work?
    ~Sven

  5. #5
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    Your original code doesn't work because sprintf() wants to write to a char array. If you inputted 'A' as the character the expected result should be that "b" should point to a zero-terminated character array that will contain 5 characters; 0, x, 4, 1 and \0.
    Since it's five character long it can't possibly fit in a single character variable.

    If this seems strange to you you should read up on strings. It can be hazardous to jump into things without having read how the things you're experiment with works in the first place.

  6. #6
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127
    oops sorry I guess it didn't paste right. Here is the most recent.
    Code:
    char* tohex(char* string){
          char hexval[10],*val;
          sprintf(hexval,"ox%x",&string);
          val=&hexval[0];
          return val;
    }
    I dont get any errors or warnings when I compile but it returns some wierd characters.
    ~Sven

  7. #7
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    That's because you return a pointer to a region of memory that goes out of scope as soon as the function ends. To make a long story short, allocate memory in the calling function and pass a pointer to this memory as a parameter to your function.

    [edit]
    Code:
    #include <stdio.h>
    
    char* tohex(char *dst, char val)
    {
       sprintf(dst, "0x%X", (unsigned)(unsigned char)val);
       return dst;
    }
    
    int main(void)
    {
       char hexval[10], value = 'A';
       puts(tohex(hexval, value));
       return 0;
    }
    
    /* my output
    0x41
    */
    Last edited by Dave_Sinkula; 02-24-2006 at 08:37 PM. Reason: Second edit: added double cast.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #8
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    hexval is local to (the stack frame of) the function. after the function returns, the frame is 'destroyed' and the address returned is invalid. pass a pointer to a character array large enough to hold the data to the function and it should work.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  9. #9
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127
    Thanks guys and now that I have tested it more the binary does not work correctly. I will keep working and post here again if I have problems. Thanks again!
    ~Sven

    EDIT~
    I ran into problems on the binary one already. I dont get any errors on the function itself but when I call it inside the main function I get an error. Here is all of the code:
    Code:
    void tobin(char* b,int n){
         char bin[17];
         int x;
         for(x=0;x<16;x++){
                           if(n & 0x8000){
                                bin[x]='1';
                           }
                           else{
                                bin[x]='0';
                           }
                           n<<=1;
         }
         bin[16]='\0';
         sprintf(b,"%s",bin);
         return b;
    }
    
    int main(){
       char binval[20];
       int value = 19;
       puts(tobin(binval,value));
       getchar();
       return 0;
    }
    The error that I get is on the bolded line in main(). The error message is "invalid use of void expression". What does that mean?
    ~Sven
    Last edited by 00Sven; 02-24-2006 at 09:08 PM.

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by 00Sven
    The error that I get is on the bolded line in main(). The error message is "invalid use of void expression". What does that mean?
    It means you should look at the return type of the function tobin.

    [edit]Something else to look at.
    Last edited by Dave_Sinkula; 02-24-2006 at 09:13 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127
    Wow I am amazed I didn't catch that. I was looking at it for about 5 minutes. I guess that I assumed that something simple like that I would have caught. Thanks!
    ~Sven

  12. #12
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127
    OK I am working on making a character conversion program with these functions and for some reason get an error. Here is the code.
    Code:
    printf("Enter your character:");
    scanf("%s",character);
    printf(tohex(converted,character));
    The error is on the printf() line it says "passing arg 2 of tohex makes an integer from a pointer without a cast". The tohex() definition is up a few posts.
    ~Sven

  13. #13
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    It appears that you have declared character as a string rather than a single character. Match the arguments to tohex with the prototype.
    Code:
    scanf("%s",character);
    This is a bad way to read strings anyway.
    FAQ > How do I... (Level 1) > Get a line of text from the user/keyboard (C)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  14. #14
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127
    OK I fixed that but it still has the same error message.
    ~Sven

  15. #15
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Well then you didn't fix it. To read a character using scanf():
    Code:
    scanf("%c", &character);
    Rather than using scanf() to read a single character, you would be better off using getchar().

    To read a string using scanf(), use %s and drop the ampersand. A string is already a pointer. You would be better off using fgets() anyway, which is covered in the FAQ.

    Besides, that's not where you error is. Your error is on this line:
    Code:
    printf(tohex(converted,character));
    argument 2 of tohex() is a character, not a string.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 06-16-2011, 11:59 AM
  2. Memo Box to Binary
    By peckitt99 in forum C++ Programming
    Replies: 8
    Last Post: 11-14-2007, 05:22 PM
  3. hex to dec to binary
    By vijlak in forum C Programming
    Replies: 2
    Last Post: 10-26-2006, 09:38 AM
  4. Printing Hex as Binary
    By Mystic_Skies in forum C Programming
    Replies: 6
    Last Post: 11-22-2004, 04:18 PM
  5. Is binary HEX?
    By Budgiekarl in forum Tech Board
    Replies: 11
    Last Post: 11-23-2003, 09:02 AM