Frank Vilea
Frank Vilea

Reputation: 8477

Convert binary to hex to decimal

I have the binary number 1010 1011. I know that this is AB in hex and I know that A = 10 and B = 11 in decimal. But how do I get from 10 and 11 in decimal to the final number of 171?

With hex I would do

             A            B
0xAB = (10 * 16^1) + (11 * 16^0) = 171

Can I do something similar with the decimal numbers to go from 10 and 11 to 171? Basically, I'm just looking for a fast way to convert any binary number without a calculator.

Upvotes: 2

Views: 4194

Answers (3)

perreal
perreal

Reputation: 97918

In C you can shift instead if multiplication to get AB from A and B:

int number = A << 4 + B;

if you store A as 1010 (decimal) and B as 1011, you can convert:

int bin2dec(unsigned int s){ 
  int v, p;
  for (v = 0, p = 1; s > 0; s=s>>1) { v = v+p*(s%2); v++; p*=2;}
  return v;
}

int number = bin2dec(A) << 4 + bin2dec(B);

Upvotes: 0

jhenderson2099
jhenderson2099

Reputation: 964

Depending on what you are trying to do, and the the language you are using, you could use the shift-left operator and add the values together.

In C++:

unsigned short val_a = (0x1010 << 4);
unsigned short val_b = 0x1011;
unsigned short result = val_a + val_b;

The result is still an unsigned short int.

Upvotes: 0

Ry-
Ry-

Reputation: 224862

I don't think there's a much easier way than A × 16 + B.

Upvotes: 4

Related Questions