0

Please help me how to code in binary like this in c++ unless other please help me........................

https://code.sololearn.com/cD6J86d5Y91C/?ref=app

30th Nov 2017, 2:02 PM
Subrahmanya Mayya
Subrahmanya Mayya - avatar
3 Réponses
+ 2
First of all you should know that each char's size is 1 byte, which equals 8 bits. Secondly you should know the ascii value of each character http://www.asciitable.com/ So now you translate every character to its binary form. For example the character 'H' has an ascii value of 72, the binary for 72 is 1001000, these are only 7 bits though, but since a character has 8 bits we fill the remaining bits with 0s ( starting at the front ). So H becomes 01001000 Next we do this for other characters, 'e' ( ascii value = 101 ) for example then translate to 01100101. Now place all these bits in a row without spaces 0100100001100101 and now this reads as "He". Now your task is to write C++ code that is able to translate this binary code to characters and print the characters. Probably the easiest way is to use the build in stoi function. the 1st parameter for stoi is the string to translate to an int the 2nd parameter expects some pointer, but this is not important so we give it a nullptr in this case the 3rd parameter is the base the string is in, binary is base 2 so we give it 2. Note that sololearn may not provide a proper stoi function so you'll have to write code to translate a string to an integer in a given base yourself if you're planning to use it on sololearn. A Hello world! program in binary would then look like this: #include <iostream> int main() { std::string bin = "010010000110010101101100011011000110111100101100001000000111011101101111011100100110110001100100001000010001010"; for( int i = 0; i < bin.size(); i += 8 ) { char c = stoi( bin.substr(i, 8), nullptr, 2 ); std::cout << c; // prints Hello, world! } } If you have questions don't hesitate to ask.
30th Nov 2017, 3:49 PM
Dennis
Dennis - avatar
+ 1
stoi is inside the string header, but it is usually included through iostream.
1st Dec 2017, 9:22 AM
Dennis
Dennis - avatar
0
Dennis Sur it has any header file?
1st Dec 2017, 1:16 AM
Subrahmanya Mayya
Subrahmanya Mayya - avatar