Converting string of 1s and 0s into binary value

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char * ptr;
    long parsed = strtol("11110111", & ptr, 2);
    printf("%lX\n", parsed);
    return EXIT_SUCCESS;
}

For larger numbers, there as a long long version, strtoll.


You can use strtol

char string[] = "1101110100110100100000";
char * end;
long int value = strtol (string,&end,2);

You can use std::bitset (if then length of your bits is known at compile time)
Though with some program you could break it up into chunks and combine.

#include <bitset>
#include <iostream>

int main()
{
    std::bitset<5>  x(std::string("01011"));

    std::cout << x << ":" << x.to_ulong() << std::endl;
}

Tags:

C++

C

Binary