如何在C中将多字符常量转换为整数? [英] How to convert multi-character constant to integer in C?
问题描述
如何将x中的多字符常量转换为整数?
How to convert multi-character constant in x to integer?
例如,我尝试将 '13'
设置为('3'+'1'<<<< 3)
,但是它无法正常工作.我的意思不是"0123"
,而是'0123'
.它可以编译,但是我不知道编译器在打印时如何获得八进制结果6014231063.我不是在寻找 atoi
,它只是将其转换为当前数字.例如, int x ='1'
将以十进制数字系统显示49.现在,我对打印 int x ='0123'
的内容很感兴趣.该任务来自编程竞赛,因此答案不应该是意外行为.
I tried for example '13'
as ('3' + '1' << 3)
, but it doesn't work properly.
I don't mean "0123"
, but '0123'
. It compiles, but I don't how did compiler gets the octal result 6014231063 when printing it. I am not looking for atoi
which just converts this to present number. For example int x = '1'
would print 49 in decimal number system. Now I am interested what would print int x = '0123'
. This task is from programming competition, so the answer shouldn't be unexpected behavior.
int main(void) {
int x = '0123';
printf("%o\n", x);
printf("%d\n", x >> 24);
printf("%d\n", x << 8 >> 24);
printf("%d\n", x & 0xff);
return 0;
}
推荐答案
如何在C语言中将多字符常量转换为整数?
How to convert multi-character constant to integer in C?
'0123'
在 int
中.
int x = '0123';
'0123'
是字符常量.在C语言中,这是常量形式之一,其类型为 int
.很少使用它,因为它的值是实现定义的.通常取决于字节顺序和字符填充(例如ASCII),如下所示:
'0123'
is a character-constant. In C, this is one of the forms of a constant and it has the type of int
. It is rarely used as its value is implementation-defined. It's usually the following depending on endianness and character codding (e.g. ASCII):
(('0'*256 + '1')*256 + `2`)*256 + '3' = 858927408 = 0x33323130
(('3'*256 + '2')*256 + `1`)*256 + '0' = 808530483 = 0x30313233
进一步:用它编写有用的可移植代码是一个挑战.当使用超过1个字符时,许多编码样式都会禁止使用它.
Further: It is a challenge to write useful portable code with it. Many coding styles bar it when used with more than 1 character.
这篇关于如何在C中将多字符常量转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!