Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shift byte array with Golang?

Tags:

go

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!

like image 602
user4611478 Avatar asked Mar 16 '23 13:03

user4611478


1 Answers

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.

like image 68
Dave C Avatar answered Mar 29 '23 06:03

Dave C