+ 1
How do we convert byte equivalent of an integer value to its original integer value in java?
Consider this piece of code: int y = 300; byte z = (byte) y; which gives me a byte value 44. Is it possible to obtain the integer value 300 from its byte equivalent value 44? If yes, how can I obtain the original value 300 from the type casted byte value 44?
5 Antworten
+ 2
No, you cannot. It is easier to understand why to consider the numbers in hex, since that maps directly to bytes.
300d is 12Ah. In hex every 2 hex digits make up 1 byte, so if we write this as 012Ah you can see 2 bytes are required to represent the value 300d.
By casting to a byte type you are 'forcing' that value into 1 byte, so the compiler throws away the most significant byte, and you are left with 2Ah, which is 44d.
If you cast back to int, it will remain 44d, since anything above 255d (FFh) cannot be stored in the byte you are casting from.
In essence, you cannot cast from a bigger type to a smaller type without loss of information, except if the value was small enough to fit in the smaller type in the first place.
For example, you can cast 123d from int to byte and back without problems, but only because 123 fits into a byte in the first place.
0
So you are recommending that normally we should not cast a bigger type number to a smaller type number if it does not fit in the range of the smaller type number in order to retain the original value of the bigger type number.
0
Hi @Ratnadeep. Yes, exactly.
0
Thanks a lot @Ettienne.
0
...