Search code examples
cintstrtol

Converting a binary string to integer


When I try and convert my binary string to int I am receiving a couple of mistakes that I can not figure out. First I am reading from a file and the leading zeros are not showing up when I convert and the new line is showing zero.

This code I am using from this questions: Convert binary string to hexadecimal string C

char* binaryString[100];

// convert binary string to integer
int value = (int)strtol(binaryString, NULL, 2);

//output string as int
printf("%i \n",value)

My txt file and what I am expecting as an output:

00000000

000000010001001000111010
00000000000000000000000000000001
101010111100110100110001001001000101

What I get:

0
0
70202
1
-1127017915

Solution

  • char *binaryString[100]; 
    

    // You are creating an array of pointers in this scenario, use char binaryString[100] instead;

    int value = (int)strtol(binaryString, NULL, 2);
    

    // 101010111100110100110001001001000101 Is a 36 bit number, int (in most implementations) is 32 bit. use long long (64 bit in visual c++) as type and strtoll as function instead.

    printf("%i \n",value)
    

    Must be printf("%lld \n", value).

    In summary:

    #include "stdio.h"
    #include "stdlib.h" // required for strtoll
    
    int main(void)
    {
        char str[100] = "101010111100110100110001001001000101";
        long long val = 0;
        val = strtoll(str, NULL, 2);
        //output string as int
        printf("%lld \n", val);
        return 0;
    }