简体   繁体   English

char数组中的整数

[英]integers in char array

I want know how integers are treated in char arrays. 我想知道如何在char数组中处理整数。 For example when we use scanf() & printf() functions for single characters we use "%c" , for string values "%s" , etc. I used "%s" for printing the char array with integers. 例如,当我们对单个字符使用scanf()printf()函数时,对于字符串值"%s"等,我们使用"%c" ,对于整数,我使用"%s"打印char数组。 But it prints some junk characters as the output. 但它会输出一些垃圾字符作为输出。

While working with integer variables directly, it's simple as: 直接使用整数变量时,它很简单:

int i = 7;
printf("%d", i);

and while working with an array of characters, you could create helper functions that will do the conversion between char* <-> int so that you end up with more portable solution: 并且在处理字符数组时,您可以创建辅助函数,这些函数将在char* <-> int之间进行转换,从而最终获得更可移植的解决方案:

int toInt(unsigned char* p) {
    return *(p + 0) << 24 | *(p + 1) << 16 | *(p + 2) << 8 | *(p + 3);
}
...
unsigned char arr[4] = {0,0,0,4};
int i = toInt(&arr[0]);
printf("%d", i);

should print 4 应该打印4

Alternatively you might use simple cast: 或者,您可以使用简单的转换:

unsigned char arr[4] = {0,0,0,4};
int* i = &arr[0];
printf("%d", *i);

but that solution will be depend on endianness. 但是该解决方案将取决于字节顺序。 On ideone.com it prints 67108864 . 在ideone.com上打印67108864

If you know the length of each phone number will be the same, you could pad out the front of the number with zeros. 如果您知道每个电话号码的长度相同,则可以在电话号码的开头加上零。 eg to pad each number out to 10 digits, putting 0's in front when necessary: 例如,将每个数字填充到10位数字,必要时将0放在前面:

int d = 123456789;
printf("%d\n", d); // prints 123456789
printf("%010d\n", d); // prints 0123456789

d = 12345678;
printf("%010d\n", d); // prints 0012345678 :-(

It's hard to guess more about the requirements without seeing the code. 如果不看代码,很难猜测更多有关需求的信息。 There's lots of examples of formatting with printf, eg: http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output 使用printf进行格式化的例子很多,例如: http : //www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM