And I red some document,In below example why we need multify value with 256.(or with shift operators)
and why need this functionality?
In the example above, the value 50,0000,007, in hexadecimal, is 0x1DCD6507. And if we break it up into four separate bytes, the byte values are 0x1D, 0xCD, 0x65, and 0x07. In decimal those four bytes are (respectively) 29, 205, 101, and 7. The biggest byte is The First One, 29, Which Represents The Value 29 * 256 * 256 * 256 = 486539264. The second biggest is The Second Byte, 205, Which Represents The Value 205 * 256 * 256 = 13434880. The Third Biggest Byte Is 101, Which Represents The Value 101 * 256 = 25856, and the littlest byte is 7, which represents the value 7 * 1 = 7. The values 486539264 + 13434880 + 25856 + 7 = 500,000,007.
You need a shift to get the 0x1d into the left position. That number can be made up from
0x1d << 0x18 | 0xcd << 0x10 | 0x 56 << 0x08 | 0x07 << 0x00 Obviously the << 0x00 in red is redundant and unnecessary because << 0 is equal to × 1. The << operator has a higher precedence than |.
Joined: Aug 12, 2008
Still I'm not able to getting,
How do we know How many positions to shift the byte value(ex: 0x1d<<0x18)?
Joined: Oct 13, 2005
32 bits to an int, that’s 0x20. So the leftmost byte has to be shifted ¾ of the width of an int, ie 0x18 (=24) bits, the middle‑to‑left byte ½ its width, 0x10 bits, etc.
Joined: Aug 12, 2008
you mean..This is the procedure/functionality you will have to consider the byte order or Endian in which multibyte numbers are stored?
Raj chiru wrote:Then,if it doesn't have anything to do with Byte Order,
How do we know How many positions to shift the byte value in multi byte order.
Java is always big-endian, so the 32 bits of a Java int will contain, reading from left to right: the sign bit + 31 value bits, with the rightmost bit being 1's.
So, in bit form, the value 1 looks like:
0 (sign) 000 0000 0000 0000 0000 0000 0000 0001
Therefore, to split it into 4 bytes you need to get them as follows:and the shift distances will always be the same, and always multiples of 8.
And to turn 4 bytes into an int, you simply do the same thing, but shift in the opposite direction.
Isn't it funny how there's always time and money enough to do it WRONG?