convert from a binary number to a hex

Let's say I build a char array of size 24.

char test[24];

and I want to fill this with 0's and 1's.  For example:

1010111100000000  etc.

Now I want to parse the first four characters and treat them as a binary number.  Continuing the example:


Now I want to convert that to the hex equivilant:

1010 would equal A

How would I do this.


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

To convert a number to an ASCII string representing its value in binary, you can use the binary AND (&) operator to test the value of the bits int the number.  For example.

Cnv2Bin(int Num,char *Dst,int Len)
   int Msk = 1;

   Dst += Len-1;
   for (int i = 0; i < Len; ++i)
      char Dig = Num & Msk?'1':'0';
      *Dst-- = Dig;
      Msg <<= 1;


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
To convert an strign representing a binary number to a strign representing a Hex number, it is best to convert each nibble of the number binary representation to an integer.  To do this

CnvBin2Int(char *Src) // -> 4 character string of the binary number to be converted.
   int Num = 0;

   for (int i =0; i < 4; ++i)
      Num <<= 1;
       if (*Src++ == '1')
   return Num;

Then to convert a binary reprentation string to a HEX representation string you would so somethign like

void CnvBin2Hex(char *Dst,char *Src,int Len)
   for (int i = 0; i < Len; ++i)
      int Nibble = CnvBin2Int(Src);
      Char Digit;

      if (Nibble < 10)
         Digit = '0' + Nibble;
         Digit = 'A' + Nibble;
      *Dst++ = Digit;
      Src += 4;

Let me know if you have any questions.
jstephe1Author Commented:
Thanks a lot.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.