6

我有 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;

为更清晰而编辑。

我选择的解决方案是:

return high*4 + (low >> (CHAR_BIT - 2));
4

2 回答 2

3

您声明HIGHand LOWas char*,但不将它们用作指针。以下代码工作正常(顺便说一句,当您不使用常量时避免使用大写标识符):

char high = 125;
char low = 12;

这就是我理解你的问题的方式(它可能更容易理解):

#include <limits.h>

int result = high + (low >> (CHAR_BIT - 2));
于 2012-12-15T17:01:53.833 回答
1

我有 2 个字符,HIGH 和 LOW,我想将它们转换为int对应于 HIGH + LOW 的 2 个左位。

你的规格不清楚。鉴于:

unsigned char HIGH = 152;
unsigned char LOW  =  12;

这可能意味着:

int result = HIGH + (LOW >> 6);   // Assuming CHAR_BIT == 8

或者它可能意味着:

int result = HIGH + (LOW & 0xC0);

或者它可能意味着:

int result = (HIGH << 2) | (LOW >> 6);

或者它可能有其他含义。对于问题中显示的值,前两个表达式产生相同的答案。

To get a more meaningful answer, you'll have to spell out the requirements much more carefully. Your actual code bears almost no discernible relationship to the requirement you specify. You have two char * variables; you initialize them to what are almost certainly invalid addresses; you don't initialize result. Your computations are, at best, odd.

于 2012-12-15T17:14:03.963 回答