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:

1010

Now I want to convert that to the hex equivilant:

1010 would equal A

How would I do this.


F

jstephe1Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
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;
   }
}

continues
0
 
nietodCommented:
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

int
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')
          ++Num;
   }
   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;
      else
         Digit = 'A' + Nibble;
      *Dst++ = Digit;
      Src += 4;
   }
}

Let me know if you have any questions.
0
 
jstephe1Author Commented:
Thanks a lot.
0
All Courses

From novice to tech pro — start learning today.