Home  >  Q&A  >  body text

java - short + byte 出现奇怪的事情

这几天在整音频相关的东西,无意间发现了一个有趣的事情

javaSystem.out.println(String.format("0xFF00 + 0xF0 = %04X",
        (short) ((short) 0xFF00 + (byte) 0xF9)));

显示的结果有点出乎意外,所以我有换成了 C/C++

cppshort a = 0xFF00;
char b = 0xF0;
printf("a + b = %X", (short)(a+b));

没错,结果跟 java 的一样,都是 FEF0

一直以来,俺都是尽量不在代码里面显式类型转换的,从教科书上来看,
byte/char 比 short 类型低级,在表达式内部应该会隐式类型转换的

可是换成两个同样是 short 类型的数值相加才能得到希望的结果,这是什么 gui

PHPzPHPz2766 days ago401

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:16:52

    short a = 0xFF00; // -256
    char b = 0xF0; // -16;
    

    So a + b is -272, that is, FEF0.
    Note that 0xF0 of char type does not equal 0x00F0 after forced conversion to short. What you need is unsigned char.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:16:52

    Both operands are 小于 int and will be implicitly converted to int for operation at the same time, which is equivalent to

    (short) ((int)(short) 0xFF00 + (int)(byte) 0xF0))
    

    Short, byte, and int are all signed

    The value of

    (int)(short) 0xFF00 is 0xFFFFFF00
    The value of (int)(byte) 0xF0 is 0xFFFFFFF0

    The result of adding

    is 0xFFFFFEFO, which overflows by one bit, and then it is forced to convert to short, and 0xFEFO

    is directly intercepted.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:16:52

    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.

     #include <stdio.h>
    
    int main(){
       unsigned char b1 = 0xF0;
       printf("unsigned char b is %X, print value is %X\n", b1, b1&0xFF);
       char b2 = 0xF0;
       printf("signed char b is %X, print value is %X\n", b2, b2&0xFF);
       unsigned short a = 0xFF00;
       unsigned char b = 0xF0;
       printf("a + b = %X\n", (unsigned short)(a+b));
    }
    
    输出
    unsigned char b is F0, print value is F0
    signed char b is FFFFFFF0, print value is F0
    a + b = FFF0
    看最后一个输出
    

    reply
    0
  • Cancelreply