BloopBloop
- Joined
- Aug 9, 2012
- Messages
- 892
- Reaction score
- 275
incase of golang:
data[0] returns a byte. Then if you shift the bits lets say (data[0] <<8) (or more than 8) , you will Always get a value that is equal to "0" ( a byte does only have 8 bits)
Example:
lets say we have a byte with value "1 "
.........128 64 32 16 8 4 2 1
bits: ...0 ...0 ...0 ...0 0 0 0 1
now lets shift the bits 8 to the left, meaning that the 1 gets 8 positions to the left
result:
256 128 64 32 16 8 4 2 1
.....1.. 0.. 0... 0 ..0 0 0 0 0
However the byte does not have the "256" , so that bit will be "dropped", (Only the first 8 bits will be taken, who are all "0")
So you first need to cast the byte to a int and then shift the bits.
Here:
this function will return the correct length, what will be incase of:
[77 212 102 212] = 43
data[0] returns a byte. Then if you shift the bits lets say (data[0] <<8) (or more than 8) , you will Always get a value that is equal to "0" ( a byte does only have 8 bits)
Example:
lets say we have a byte with value "1 "
.........128 64 32 16 8 4 2 1
bits: ...0 ...0 ...0 ...0 0 0 0 1
now lets shift the bits 8 to the left, meaning that the 1 gets 8 positions to the left
result:
256 128 64 32 16 8 4 2 1
.....1.. 0.. 0... 0 ..0 0 0 0 0
However the byte does not have the "256" , so that bit will be "dropped", (Only the first 8 bits will be taken, who are all "0")
So you first need to cast the byte to a int and then shift the bits.
Here:
this function will return the correct length, what will be incase of:
[77 212 102 212] = 43
Code:
func GetHeaderLength(data []byte) uint16 {
var num = ((int32(data[0])) | (int32(data[1]) << 8))|(int32(data[2]) << 16) |(int32(data[3]) << 24)
return uint16((num >> 16) ^ (num & 0xFFFF))
}
Last edited: