C Tidbit: Reading in “binary” from text file with strtol
Last night, I was working on an assignment for my cryptography class (writing SPN and Feistel ciphers in C), and I was looking for a way to read in “binary” from a text file. I.e. the file itself was not a binary file, but rather I was reading ASCII 0 and 1 characters from the file and interpreting them in my program. After a bit of searching, I came across the man page for atoi, which states that its behavior is the same as:
strtol(nptr, (char **) NULL, 10);
I’ve never seen this “strtol” before, so I went and looked at its man page, and it turns out that this is the magic function that let me do what I wanted to do. That last argument is the numerical base, so I just do something like so:
long int myint = strtol(binary_str, NULL, 2);
Of course, this is after reading in a series of binary strings as character pointers from the file with fscanf. I.e. in the above, binary_str is a char * that contains something like “01101001″.
I just thought this was worth sharing, since without knowing about this function, anyone trying to do this has to end up writing annoying binary/decimal conversion functions. Not particularly difficult, but annoying nonetheless when the functionality is right there.




