tags:

views:

1158

answers:

4

I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?

+9  A: 

You can use strtol

char string[] = "1101110100110100100000";
char * end;
long int value = strtol (string,&end,2);
Torlack
+21  A: 
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char * ptr;
    long parsed = strtol("11110111", & ptr, 2);
    printf("%lX\n", parsed);
    return EXIT_SUCCESS;
}
jkramer
This looks about right. My only concern was on very large strings, which thinking about it now, would probably need some custom code anyhow.
grosauro
Besides strtol there's also stroll (two L) for "long long" integers.
jkramer
Ah, now I see your point. The string length shouldn't be a problem as long as the resulting number fits into the long or long long integer.
jkramer
+11  A: 

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;
}
Martin York
+6  A: 

You can use Boost Dynamic Bitset:

boost::dynamic_bitset<>  x(std::string("01011"));
std::cout << x << ":" << x.to_ulong() << std::endl;
Rob