将0附加到C中的整数 [英] Appending 0 to an integer in C
问题描述
我的整数为123.
如何将0加到此并获得0123。
我不想只打印。我想永久追加0.
怎么办?
提前感谢
我的尝试:
我无法尝试。我可以像%04d那样打印但是无法分配为值
你不能。
数字不会像:它们存储在一个具有固定位数的存储单元中,通常是8:8位(字节),16位(短),32位(int或int32),64位(long或int64)的倍数)。在该存储器中,所有位总是被使用 - 它们总是为零或一个,具体取决于存储的数量。
将数字1存储在16位(短)值中 - 因为这里写的比32位整数更容易 - 你会得到:
0000000000000001123你会得到
0000000001111100正如您所看到的,您的号码中已经有大量前导零值!
数字(无论大小或类型 - 浮点数,双精度数和十进制数值也存储为位值)没有前导零的概念,它们仅在应用格式时才可用转换为字符串时的数字(通常用于呈现给用户)。
您不能将前导零添加到保留为整数的整数:0123与000000000000123或123
<相同的整数br>
引用:我无法尝试。我可以像%04d那样打印它但不能指定为值
你只能用字符串来做,这就是数字的表示。例如
int a = 123 跨度>;
char sa [ 5 ];
snprintf(sa, sizeof (sa), %04D跨度>,一个);
Hi,
I have an integer as 123.
How to append 0 to this and get 0123 .
I dont want just printing. I want to permanently append 0.
How to do?
thanks in advance
What I have tried:
I am unable to try. I can print it just like %04d but unable to assign as value解决方案You can't.
Numbers aren't stored like that: they are stored in a memory location which has a fixed number of bits, normally a multiple of 8: 8 bits (byte), 16 bits (short), 32 bits (int, or int32), 64 bits (long or int64). And in that memory, all the bits are always used - they are always either a zero or a one depending on the number being stored.
To store the number 1 in a 16 bit (short) value - becuase it's easier to write down here than a 32 bit integer - you would get:
0000000000000001For 123 you would get
0000000001111100As you can see, you already have a significant number of "leading zero" values in your number!
Numbers (regardless of size, or type - float, double, and decimal values are stored as bit values as well) do not have a concept of leading zeros, they are only every available when formatting is applied to a number when it is converted to a string (normally for presentation to a user).
You cannot add a "leading zero" to a integer which is preserved while it remains a number: 0123 is the same integer as 000000000000123 or 123
Quote:I am unable to try. I can print it just like %04d but unable to assign as value
You can only do it with a string, that is the representation of the number. For example
int a = 123; char sa[5]; snprintf(sa, sizeof(sa), "%04d",a);
这篇关于将0附加到C中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!