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