Understanding Java bytes

后端 未结 6 911
抹茶落季
抹茶落季 2020-12-31 18:48

So at work yesterday, I had to write an application to count the pages in an AFP file. So I dusted off my MO:DCA spec PDF and found the structured field BPG (Begin Pag

6条回答
  •  抹茶落季
    2020-12-31 19:21

    In order to obtain the binary representation of a negative number you calculate two's complement:

    • Get the binary representation of the positive number
    • Invert all the bits
    • Add one

    Let's do -72 as an example:

    0100 1000    72
    1011 0111    All bits inverted
    1011 1000    Add one
    

    So the binary (8-bit) representation of -72 is 10111000.

    What is actually happening to you is the following: You file has a byte with value 10111000. When interpreted as an unsigned byte (which is probably what you want), this is 88.

    In Java, when this byte is used as an int (for example because read() returns an int, or because of implicit promotion), it will be interpreted as a signed byte, and sign-extended to 11111111 11111111 11111111 10111000. This is an integer with value -72.

    By ANDing with 0xff you retain only the lowest 8 bits, so your integer is now 00000000 00000000 00000000 10111000, which is 88.

提交回复
热议问题