简体   繁体   中英

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 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:

char *end = NULL;
int n = strtol(buffer, &end, 10);
if (*end != '\0') {
    // buffer contains unconvertible characters
}
// do something with n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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