Understanding Java bytes

后端 未结 6 872
抹茶落季
抹茶落季 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:13

    I guess the magic here is that the byte is stored in a bigger container, likely a 32 bit int. And if the byte was interpreted as being a signed byte it gets expanded to represent the same number in the 32 bit int, that is if the most significant bit (the first one) of the byte is a 1 then in the 32 bit int all the bits left of that 1 are also turned to 1 (that's due to the way negative numbers are represented, two's complement).

    Now, if you & 0xFF that int you cut off those 1's and end up with a "positive" int representing the byte value you've read.

提交回复
热议问题