Trying to understand the math of this code snippet. A token is provided which is always 8 digits. It enters a class typed as a long. The token is being broken up into separate bytes to be sent over a stream.
long token = 85838276;
byte cp[] = {
1, 0, 0, 0, 0
};
cp[4] = (byte)(int)token; // not sure what would become of token
cp[3] = (byte)(int)(token >> 8);
cp[2] = (byte)(int)(token >> 16);
cp[1] = (byte)(int)(token >> 24);
I understand the typecasting (byte) part but not having (byte)(int) together. Does the token which is of type long, have to step down one simple type at a time? Couldn’t you omit the (int) and have the same result?
Is the order important or is it just written from cp[4] to cp[1] for clarity.
I realize the token in cp[4] will not be equal to the original value since the max value the byte type can hold is 127. Is it possible to recreate the original token once it has reached its destination?
Lastly I would like to recreate this in php. I know a string is already a byte stream. Each character sent would be one byte. Do I need to send a string of characters with each character being equal to integer value it represents. Such as a for 41
Updated:
So according to Louis Wasserman’s answer, when type cast to byte, only the last byte is kept.
Token in binary: 101000111011100100111000100 // cp[4] = 11000100
Token shifted 08: 1010001110111001001 // cp[3] = 11001001
Token shifted 16: 10100011101 // cp[2] = 00011101
Token shifted 24: 101 // cp[1] = 101
As far as I can tell,
(byte) (int)is equivalent to(byte)in this context.That wouldn’t be true for all double casts, but it seems true here. They’re both “narrowing” cast conversions.