Binary Conversion

Calculate the minimum number of binary digits needed to represent a three digit hexadecimal value.
How many possible values are represented by a binary digit?
How many bits are required to represent those values?

How many possible values are represented by a hexadecimal digit?
How many bits are required to represent those values?
This exact topic has an active thread running.
> the minimum number of binary digits needed to represent a three digit hexadecimal value

If leading zeroes are allowed, minimum is one binary digit.
If not, the minimum is nine binary digits.
In either case, the maximum is 12 binary digits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

int bits_required( char hex_digit )
{
    switch(hex_digit)
    {
        case '0' : case '1' : return 1 ; // 0 or 1
        case '2' : case '3' : return 2 ; // 10 or 11
        case '4' : case '5' : case '6': case '7': return 3 ; // 100, 101, 110, 111
        default : return 4 ; // 8-f: 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
    }
}

// hex_digit_1 is the most significant (left-most) digit
int bits_required( char hex_digit_1, char hex_digit_2, char hex_digit_3 )
{
    if( hex_digit_1 != '0' ) return bits_required(hex_digit_1) + 8 ;
    if( hex_digit_2 != '0' ) return bits_required(hex_digit_2) + 4 ;
    return bits_required(hex_digit_3) ;
}

int bits_required( const char hex_digits[3] )
{ return bits_required( hex_digits[0], hex_digits[1], hex_digits[2] ) ; }

int main()
{
    for( const char* hex : { "001", "006", "00d", "01f", "09b", "1ff", "300", "7ff", "800" } )
        std::cout << "0x" << hex << ' ' << bits_required(hex) << '\n' ;
}

0x001 1
0x006 3
0x00d 4
0x01f 5
0x09b 8
0x1ff 9
0x300 10
0x7ff 11
0x800 12

http://coliru.stacked-crooked.com/a/e3d8c86b6ade6755
OMG! Can I not have a coded version please but calculated one?
http://www.cplusplus.com/forum/general/214560/#msg998838

@masterKay - why are you asking the same question twice?
Last edited on
whats to calculate?? Apart from already having done that in the other thread,
3 half bytes. 3*4 is 12. That is the max. The other solutions show what to do if you want to know it for each value, half of which use less than 12.
Last edited on
Topic archived. No new replies allowed.