Leo*_*Leo 6 c int casting char
我有 2 个字符:HIGH 和 LOW,我想将它们转换为对应于 HIGH + LOW 的 2 个左位的 int。
我试过类似的东西:
unsigned char high;
unsigned char low;
high = 128; // 10000000
low= 128; // 10000000
int result; (should be high 10000000 + 2 left bites of low 10 = 1000000010)
// To do
return result;
Run Code Online (Sandbox Code Playgroud)
编辑为更清晰。
我选择的解决方案是:
return high*4 + (low >> (CHAR_BIT - 2));
Run Code Online (Sandbox Code Playgroud)
您将HIGH
and声明LOW
为char*
,但不将它们用作指针。以下代码工作正常(顺便说一句,当您不使用常量时避免使用大写标识符):
char high = 125;
char low = 12;
Run Code Online (Sandbox Code Playgroud)
这就是我对你的问题的理解(可能更容易理解):
#include <limits.h>
int result = high + (low >> (CHAR_BIT - 2));
Run Code Online (Sandbox Code Playgroud)