C中的2个字符 [英] 2 Chars to Short in C
问题描述
我有2个字符.
Char 128
和Char 2
.
Char 128
and Char 2
.
如何将这些字符转换为C语言中的短 640
?
How do I turn these chars into the Short 640
in C?
我尝试过
unsigned short getShort(unsigned char* array, int offset)
{
short returnVal;
char* a = slice(array, offset, offset+2);
memcpy(&returnVal, a, 2);
free(a);
return returnVal;
}
但这没用,只是将其显示为 128
.首选方法是什么?
But that didn't work, it just displays it as 128
. What's the preferred method?
推荐答案
我发现接受的答案几乎是正确的,除了我遇到一个错误,有时结果的最高字节为 0xff
...
I found that the accepted answer was nearly correct, except i'd run into a bug where sometimes the top byte of the result would be 0xff
...
我意识到这是由于C符号扩展引起的.如果第二个字符为> = 0x80
,则将 0x80
转换为短字符将变为 0xff80
.对任何内容执行 0xff80
的或"会导致最高字节保留为 0xff
.
I realized this was because of C sign extension. if the second char is >= 0x80
, then converting 0x80
to a short becomes 0xff80
. Performing an 'or' of 0xff80
with anything results in the top byte remaining 0xff
.
以下解决方案通过在b的隐式转换为short的过程中将b的高位字节清零来避免该问题.
The following solution avoids the issue by zeroing out the top byte of b during its implicit conversion to a short.
short c = (((short)a) << 8) | (0x00ff & b);
这篇关于C中的2个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!