Hex to binary in C

Programming, for all ages and all languages.
Post Reply
srg_13

Hex to binary in C

Post by srg_13 »

Hi.
Does anyone here know how to convert hex to binary in C?? I need to do this in my operating system, so it cannot use any external commands, except for the ones I have implemented and possibly the built in DJGPP commands. Is this possible??? The numbers I wish to convert are like 0x06F and so on.

Thanks in advance,

-Stephen
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:Hex to binary in C

Post by Candy »

Code: Select all

void IntToHex(unsigned int number, char *buffer) {
  for (int i = 0; i<sizeof(unsigned int) * 2; i++) {
    buffer[i] = ((number >> (4*i)) & 0xF) + '0';
    if (buffer[i] > '9') buffer[i] += 'A' - '9';
  }
  buffer[i] = '\0';
}
If you cannot do this yourself you should learn a lot more C programming before trying OS development in C.

Note that this version is compatible for all lengths of variables, assumes the buffer is large enough and doesn't rely on specific ASCII values.

I know I shouldn't post code to code requests from principle, but this is just so basic a request that I can't imagine this code having any value. Also, I think this code is also in the OSFAQ, or at least should be.

[edit] conciseness is more important than generating "0x" in front of it.[/edit]
AR

Re:Hex to binary in C

Post by AR »

"Hex to binary"? As in Base 2? Or just into an Integer? Or did you really mean into Hex?

If you want hex to binary then you'd want to break this into steps, first you'll need an atoi() equivalent for hex then take the integer and run it through a convertor.

Code: Select all

#include <stdio.h>

const char *CharRep = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

unsigned int HexToInt(const char *Hex)
{
    //Assuming the "0x" prefix has been cut off by the caller
    unsigned int RetVal = 0;
    int i;

    while(*Hex != '\0')  //Loop until end of Hex Number String
    {
        for(i = 0 ; CharRep[i] != '\0' ; ++i)  //Loop through the number representations
        {
            if( CharRep[i] == *Hex ) break;
        }
        RetVal = (RetVal << 4) + i;  //Warning, typing "0xG" will succeed but yield weird results

        ++Hex;
    }

    return RetVal;
}

// Prints an unsigned int using recursion
void PrintUNum(unsigned int num, unsigned int base)
{
    if( num / base )
       PrintUNum( num / base, base );

    putchar( CharRep[num % base] );
}

int main()
{
    unsigned int Val = HexToInt( "06F" );
    PrintUNum( Val, 2 );

    return 0;
}
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:Hex to binary in C

Post by Candy »

Code: Select all

int HexToInt(const char *data) {
  int cval = 0;
  while (*data != '\0') {
    cval <<= 4;
    int tval = *data;
    tval -= '0';
    if (tval > 9) tval -= ('A' - '9');
    if (tval > 15) tval -= ('a' - 'A');
    cval += tval;
  }
  return cval;
}
similar to the previous one..

Note for self, read properly next time.
srg_13

Re:Hex to binary in C

Post by srg_13 »

Thanks a lot.

-Stephen

P.S. It is not because I don't know enough about C that I cannot write this. I just don't know the how the hex number system works very well.
User avatar
bubach
Member
Member
Posts: 1223
Joined: Sat Oct 23, 2004 11:00 pm
Location: Sweden
Contact:

Re:Hex to binary in C

Post by bubach »

You know C but not hex.. Hmm.. :)
"Simplicity is the ultimate sophistication."
http://bos.asmhackers.net/ - GitHub
Kemp

Re:Hex to binary in C

Post by Kemp »

Hex is very simple to understand, it just goes from 0 to F rather than 0 to 9, ie:

0 1 2 3 4 5 6 7 8 9 A B C D E F

Called base 16 as it has 16 available values per digit. (Textual) Conversion to and from binary is made easier then either of them to/from denary (base 10, our "normal" system) because you can split the binary number into groups of four digits and each one will correspond to one hex digit, eg:

100101110100

can be split into

1001 0111 0100

and then converted into

9 7 4 (974h)
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:Hex to binary in C

Post by Solar »

I finished the corresponding functions (strtol() and brethren) in the PDCLib (latest CVS, not yet packaged / released). It's a bit more complex than the snippet provided by Candy, but it's complete with range checking, and works as expected for any other numerical base between 2 and 36.

The point to start would be strtol.c. You will also need <limits.h> (to define LONG_MAX, LONG_MIN), strtox_prelim.c and strtox_main.c, if you want to use it stand-alone (i.e. without the rest of PDCLib).

strtox_main.c will require some tinkering - replace _PDCLIB_uintmax_t with a large-enough unsigned integer type. You'll also need a "digits array" (i.e., "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", called _PDCLIB_digits in my code) and working versions of isspace(), toupper() and memchr() - but those should be easy enough.

The upside is, once you got that running, adding strtoul(), strtoll() and strtoull() is a piece of cake. 8) And don't complain, I know the hacking with _prelim() and _main() isn't really nice, but it's the only way I could come up with not to use virtually identical code in several places, it works, and I'll probably simplify it later. 8)

It's PD, so do with it whatever you like. ;-)
Every good solution is obvious once you've found it.
Post Reply