简体   繁体   English

关于在C ++中通过ASCII将文本转换为十六进制

[英]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). 因此,我研究了如何根据ASCII将文本转换为十六进制,并且有一个可行的解决方案(在此处提出)。 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. 在C ++中,字符长8位。

If you '&' it with 15 (binary 1111 ), then the least significant 4 bits are outputted to the first digit. 如果用15 '&' (二进制1111 ),则最低有效4位将输出到第一位。

When you apply right shift by 4 , then it is equivalent of dividing the character value by 16 . 当您将right shift by 4 ,则等效于将字符值除以16 This gives you the most significant 4 bits for second digit. 这为您提供了第二位的最高有效4位。

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. 一旦计算出上述数字值,就从具有所有字符在其相应位置的常量字符串str1中提取所需的字符。

"Characters in a string" are not characters (individual strings of one character only). “字符串中的字符”不是字符 (仅一个字符的单个字符串)。 In some programming languages they are. 在某些编程语言中,它们是。 In Javascript, for example, 以Javascript为例,

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

returns "t" . 返回"t"

In C and C++, however, 'strings' are arrays of 8-bit characters; 但是,在C和C ++中,“字符串”是8位字符的数组。 each element of the array is an 8-bit number from 0..255. 数组的每个元素都是从0..255开始的8位数字。

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. 在ASCII中,字符“ 0”是整数48。C++在许多情况下都隐式进行此转换,包括代码中的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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