How are integers cast to bytes in Java?

后端 未结 8 1182
我在风中等你
我在风中等你 2020-11-27 21:02

I know Java doesn\'t allow unsigned types, so I was wondering how it casts an integer to a byte. Say I have an integer a with a value of 255 and I cast the integer to a byte

8条回答
  •  执念已碎
    2020-11-27 21:21

    Byte is 8 bit. 8 bit can represent 256 numbers.(2 raise to 8=256)
    Now first bit is used for sign. [if positive then first bit=0, if negative first bit= 1]
    let's say you want to convert integer 1099 to byte. just devide 1099 by 256. remainder is your byte representation of int
    examples
    1099/256 => remainder= 75
    -1099/256 =>remainder=-75
    2049/256 => remainder= 1
    reason why? look at this image http://i.stack.imgur.com/FYwqr.png

提交回复
热议问题