Here simple working code to left shift first bit of a byte
package main
import (
"fmt"
)
type Byte byte
func SL(b Byte) Byte {
if b&0x80 == 0x80 {
b <<= 1
b ^= 0x01
} else {
b <<= 1
}
return b
}
func main() {
var b Byte
b = 0xD3
fmt.Printf("old byte %#08b\n", b) // 11010011
c := SL(b)
fmt.Printf("new byte %#08b", c) // 10100111
}
What should I do to shift array of bytes, like
type Byte [2]byte
?
Thanks for advance!
You appear to want to rotate, not shift. Any particular reason you aren't using a uint16
type instead of [2]byte
?
Anyway, if you really want [2]byte
, this is simpler and doesn't branch:
func rol(v [2]byte) [2]byte {
x := int(v[0])<<8 | int(v[1])
x <<= 1
v[0] = byte(x >> 8)
v[1] = byte((x & 0xff) | x>>16)
return v
}
If you want to do such operations on an arbitrary large number of bits you could use math/big
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With