这几天在整音频相关的东西,无意间发现了一个有趣的事情
java
System.out.println(String.format("0xFF00 + 0xF0 = %04X", (short) ((short) 0xFF00 + (byte) 0xF9)));
显示的结果有点出乎意外,所以我有换成了 C/C++
cpp
short a = 0xFF00; char b = 0xF0; printf("a + b = %X", (short)(a+b));
没错,结果跟 java 的一样,都是 FEF0
一直以来,俺都是尽量不在代码里面显式类型转换的,从教科书上来看,
byte/char 比 short 类型低级,在表达式内部应该会隐式类型转换的
可是换成两个同样是 short 类型的数值相加才能得到希望的结果,这是什么 gui
So
a + b
is-272
, that is,FEF0
.Note that
0xF0
of char type does not equal0x00F0
after forced conversion to short. What you need is unsigned char.Both operands are
小于
int
and will be implicitly converted toint
for operation at the same time, which is equivalent toShort, byte, and int are all signed
The value of
The result of adding(int)(short) 0xFF00
is0xFFFFFF00
The value of
(int)(byte) 0xF0
is0xFFFFFFF0
is
is directly intercepted.0xFFFFFEFO
, which overflows by one bit, and then it is forced to convert toshort
, and0xFEFO
The range of char is -128 to 127, so if 0xF0 is a signed char, the gcc compiler performs 4-byte alignment by default, and adds 0xFFFFFFF in front, while the range of unsigned char is 0~255, complete the When the front is 0.