알고리즘/codefights

58>messageFromBinaryCode

Diademata 2018. 4. 13. 00:59
반응형

You are taking part in an Escape Room challenge designed specifically for programmers. In your efforts to find a clue, you've found a binary code written on the wall behind a vase, and realized that it must be an encrypted message. After some thought, your first guess is that each consecutive 8 bits of the code stand for the character with the corresponding extended ASCII code.


Assuming that your hunch is correct, decode the message.


Example


For code = "010010000110010101101100011011000110111100100001", the output should be

messageFromBinaryCode(code) = "Hello!".


The first 8 characters of the code are 01001000, which is 72 in the binary numeral system. 72 stands for H in the ASCII-table, so the first letter is H.

Other letters can be obtained in the same manner. 


code >>


std::string messageFromBinaryCode(std::string code) {

std::string output;

for (int i = 0; i < code.size(); i += 8)

{

int dec = 0;

for (int ii = i; ii < i + 8; ii++)

dec |= (code[ii] - '0' << i + 7 - ii);

output.push_back((char)(dec));

}

return output;

}

반응형

'알고리즘 > codefights' 카테고리의 다른 글

60>sudoku  (0) 2018.04.14
59>spiralNumbers  (0) 2018.04.14
57>fileNaming  (0) 2018.04.13
56>digitsProduct  (0) 2018.04.12
55>differentSquares  (0) 2018.03.28