2

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.

Brad Rem
  • 6,036
  • 2
  • 25
  • 50
Frank Vilea
  • 8,323
  • 20
  • 65
  • 86
  • I'm using C for these things. – Frank Vilea Mar 24 '12 at 15:41
  • Excellent, so do you have code to show us for how you're trying to do your conversions? – Brad Rem Mar 24 '12 at 16:10
  • how do you store the number 1010 1011? – perreal Mar 24 '12 at 16:12
  • [C convert hex to decimal](http://stackoverflow.com/questions/676763/c-convert-hex-to-decimal-format) or better yet [Converting dec/binary](http://stackoverflow.com/a/2548374/1243316) – Brad Rem Mar 24 '12 at 16:12
  • @BradRem Ehm.. I'm not actually looking for a library or anything, I'm simply learning about binary/hex and decimal because I'm new to bitwise operations and I'm trying to make sense of everything. – Frank Vilea Mar 24 '12 at 16:22
  • @perreal Not sure if it is compiler dependent, but you can store it in C using 0b10101011. E.g. unsigned char myByte = 0b10101011; – Frank Vilea Mar 24 '12 at 16:23

3 Answers3

4

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

Ry-
  • 218,210
  • 55
  • 464
  • 476
0

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.

jhenderson2099
  • 956
  • 8
  • 17
0

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);
perreal
  • 94,503
  • 21
  • 155
  • 181