C语言 十六进制数可以加/减十进制数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28445459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:44:28  来源:igfitidea点击:

Can hexadecimal numbers be added/subtracted with decimal numbers?

cbinaryhexdecimal

提问by Vimzy

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?

在用 C 编程时,假设我有整数 h 作为十六进制值,整数 d 作为十进制数。我可以在 h 和 d 之间做加法或减法吗?或者他们必须在同一个数字系统中?

回答by Jonathan Leffler

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 intvalue that was assigned the appropriate value:

这将十进制与十六进制和八进制混合。无论如何,在计算发生之前,这些值都被转换为二进制(并且编译器将在本例中进行计算;它不会在运行时进行评估)。并且任何常量都可以替换int为分配了适当值的值:

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

回答by Iharob Al Asimi

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.

您使用的表示形式无关紧要,毕竟它最终会全部转换为二进制。