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?
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
The main reason why we use sigmoid function is because it exists between (0 to 1).
WriteFile function (MSDN)
#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 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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With