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?

[Webinar] Streamline your web hosting managementRegister Today

nietodConnect With a Mentor Commented:
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;

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.
All Courses

From novice to tech pro — start learning today.