Convert binary to hex to decimal

最后都变了- 提交于 2019-12-10 23:38:13

问题


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.


回答1:


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




回答2:


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.




回答3:


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);


来源:https://stackoverflow.com/questions/9852917/convert-binary-to-hex-to-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!