简体   繁体   中英

Regarding conversion of text to hex via ASCII in C++

So, I've looked up how to do conversion from text to hexadecimal according to ASCII, and I have a working solution (proposed on here). My problem is that I don't understand why it works. Here's my code:

#include <string>
#include <iostream>

int main() 
{
    std::string str1 = "0123456789ABCDEF";
    std::string output[2];
        std::string input;
    std::getline(std::cin, input);
    output[0] = str1[input[0] & 15];
    output[1] = str1[input[0] >> 4];    
    std::cout << output[1] << output[0] << std::endl;
}

Which is all well and good - it returns the hexadecimal value for single characters, however, what I don't understand is this:

input[0] & 15
input[0] >> 4

How can you perform bitwise operations on a character from a string? And why does it oh-so-nicely return the exact values we're after?

Thanks for any help! :)

In C++ a character is 8 bits long.

If you '&' it with 15 (binary 1111 ), then the least significant 4 bits are outputted to the first digit.

When you apply right shift by 4 , then it is equivalent of dividing the character value by 16 . This gives you the most significant 4 bits for second digit.

Once the above digit values are calculated, the required character is picked up from the constant string str1 having all the characters in their respective positions.

"Characters in a string" are not characters (individual strings of one character only). In some programming languages they are. In Javascript, for example,

var string = "testing 1,2,3";
var character = string[0];

returns "t" .

In C and C++, however, 'strings' are arrays of 8-bit characters; each element of the array is an 8-bit number from 0..255.

Characters are just integers. In ASCII the character '0' is the integer 48. C++ makes this conversion implicitly in many contexts, including the one in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM