[英]How do I convert a char array to an int in C?
I am working on some previously written code.我正在处理一些以前编写的代码。 The code is currently reading input to a char array buffer, but I now need to be able to use bit masking and shifting to retain specific subsets of integers in the file.
该代码当前正在读取字符数组缓冲区的输入,但我现在需要能够使用位掩码和移位来保留文件中的特定整数子集。 I already have code for the bit masking and shifting written, but I cannot figure out how to convert the char array to an int.
我已经编写了位屏蔽和移位的代码,但我不知道如何将 char 数组转换为 int。
char buffer[5];
FILE *fp = fopen(inputFile, "r");
while (fgets(buffer, 5, fp) != NULL) {
//Perform bit masking/shifting operations
}
You can use standard function strtol
to convert strings to integers:您可以使用标准函数
strtol
将字符串转换为整数:
char *end = NULL;
int n = strtol(buffer, &end, 10);
if (*end != '\0') {
// buffer contains unconvertible characters
}
// do something with n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.