SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Jesper de Jong wrote:To understand exactly how this works, you have to understand that a byte in Java is an 8-bit signed integer that is stored in two's complement format. Because of this, the range of values that can be stored in a byte goes from -128 to +127.
If you have an integer value that is outside of this range and you cast it to byte, then the higher bits will be cut off the value and the lower eight bits will be interpreted as a byte. Let's look at what this means for the values you tried:
127 = 0000 0000 0000 0000 0000 0000 0111 1111 -> take lower 8 bits: 0111 1111 -> fits in the range of byte, so this will remain 127
128 = 0000 0000 0000 0000 0000 0000 1111 1111 -> take lower 8 bits: 1111 1111 -> when interpreted as a byte in two's complement, this is -128
256 = 0000 0000 0000 0000 0000 0001 0000 0000 -> take lower 8 bits: 0000 0000 -> zero
Rob Spoor wrote:
Edit: wow, within a few minutes we have 5 times the same answer
Afraid not. That is S&M numbering you are thinking of. S&M means sign and magnitude, which is usually only used for floating point numbers, including the IEEE754 format.Ralph Cook wrote:. . . The highest-order bit in a signed integer is the sign, 1 for negative, 0 for positive. . . .
Agreed. Even though the wikipedia article about two’s complement uses the term “sign bit”.Ralph Cook wrote: . . . It isn't really a sign bit the way floating-point sign bits are. . . .
Lasagna is spaghetti flvored cake. Just like this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
|