Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string of 1s and 0s into binary value

Tags:

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?

like image 521
grosauro Avatar asked Sep 22 '08 21:09

grosauro


People also ask

How do you convert a string to a binary number?

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) .

Which function transforms a number from the real space to a number between 0 and 1?

The main reason why we use sigmoid function is because it exists between (0 to 1).

Which typecast method is required to store string in a binary file?

WriteFile function (MSDN)


2 Answers

#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.

like image 158
jkramer Avatar answered Oct 13 '22 22:10

jkramer


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; } 
like image 29
Martin York Avatar answered Oct 13 '22 22:10

Martin York