Can hexadecimal numbers be added/subtracted with decimal numbers?

梦想与她 提交于 2019-12-22 09:29:09

问题


When programming in C, say if I have integer h as a hexadecimal value and integer d as a decimal number. Can I do addition or subtraction between h and d? Or do they have have to be in the same number system?


回答1:


Yes, you can write:

int x = 100 - 0x100 + 0100;

That mixes decimal with hex and octal. The values are all converted to binary anyway before the calculation occurs (and the compiler will do the calculation in this example; it won't be evaluated at runtime). And any of the constants can be replaced by an int value that was assigned the appropriate value:

int d = 100;
int h = 0x100;
int o = 0100;
int x = d + h + o;



回答2:


Yes they can, for example

int x;
x = 0x0F + 10;
printf("%d\n", x);

Output:

25

the representation you use doesn't matter, it will be ultimately all converted to binary after all.



来源:https://stackoverflow.com/questions/28445459/can-hexadecimal-numbers-be-added-subtracted-with-decimal-numbers

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