[英]Two pieces of code with the same logic. One gives expected output while the other does not
char xtime(char m)
{
//calculates the m value by checking m,if m is less than 0x80 hexadecimal
// then it is left shifted else it is left shifted and xor'ed with 0x1b.
if(m<0x80)
{
m<<=1;
} else {
m=(((m)<<1)^0x1b);
}
printf("%#01x ",m&0xff);
return m;
}
This code doesnt show the expected output if m=0x80(which is 0x1b),it gives the output as 0 in hexadecimal. 如果m = 0x80(即0x1b),则此代码未显示预期的输出,它将输出以十六进制表示为0。
#define xtime(a) (((a)<0x80)?(a)<<1:(((a)<<1)^0x1b) )
This code works and gives the expected result . 此代码有效,并给出了预期的结果。
Could you please help as to what is wrong with the functional code and how is it solved in the second code. 关于功能代码的问题以及如何在第二代码中解决,请您提供帮助。
Assuming that in your environment 假设在您的环境中
char
is signed char
已签名 char
is 8-bit long char
是8位长 0x80
is too big to store into char
variable, and it will be interpreted as -128
. 0x80
太大,无法存储到char
变量中,它将被解释为-128
。 -128
is smaller than 0x80
, so m <<= 1;
-128
小于0x80
,因此m <<= 1;
is executed. 被执行。 The result of this shift is -256
, and its binary reprensentation is 0xffffff00
, and m
will get the last 8 bits, which is 0
. 此移位的结果是-256
,其二进制表示形式是0xffffff00
,并且m
将获得最后8位,即0
。 That is what you get. 那就是你得到的。
The macro will work if 0x80
is passed to a
, because the calculation will be done using int
, and int
can hold integers upto at least 32767
. 如果将0x80
传递给a
,则该宏将起作用,因为该计算将使用int
完成,并且int
最多可容纳至少32767
整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.