How can I merge two ASCII characters? [closed]

非 Y 不嫁゛ 提交于 2020-05-09 17:27:16

问题


I want to merge two characters and print them via a single variable by using ASCII (refer to the image below):

[1]: https://i.stack.imgur.com/TWodP.jpgenter image description hereenter image description here


回答1:


try this if your machine is little endian

unsigned int C = (b << 8) | a;
printf("%s",&C);

otherwise if your machine is big endian try

unsigned int C = (a << 24) | (b<<16);
printf("%s",&C);



回答2:


Based on my comment, but improved by Jonathan's input, I propose to do this:

int C;
C= (((unsigned char)a)<<8)|((unsigned char)b);

You have already tried the commented version to be helpful, this one is basically the same, just being robust against potentially negative values of a and b (which I considered out of scope, but Jonathan is right in being as safe as possible).

As for the explanation:

The << 8 part, a so-called bitshift left, moves a value by 8 bit towards the MSBs.
I.e. a 00000000010000001 becomes a 01000000100000000.

To be safe from negative value (see below why that is important), the value is first type-casted to unsigned char. That is the part ((unsigned char)a). Note that I tend to be generous when it comes to using (), some people do not like that. This is done for both values.

With values 'A' and 'B' we end up with

0100000100000000 and 0000000001000010.

The next part uses a bitwise OR (|), in contrast to a logical OR (||).
The result is

0100000101000010, which is what I understand to be your goal.

The importance of protecting against negative input is this. Any negative 8bit value has the MSB set and when cast to a wider data type will end up with all 8 new high bits set. This is because of the representation of negative values in integers in 2-compliment.

The final conversion to the desired wider data type is as Jonathan explains:

If you have (unsigned char)A << 8 as a term, then the unsigned char value is extended to int before the shift occurs, and the result is an int.



来源:https://stackoverflow.com/questions/60893188/how-can-i-merge-two-ascii-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!