如何使用Golang移位字节数组?

4
这里是将字节的第一位左移的简单工作代码。
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
}

我应该如何移位字节数组,比如 type Byte [2]byte

提前致谢!


2
注意,在Go语言中,除了特殊情况外,切片比数组更常见。此外,在这种情况下,请考虑使用uint16 - Dave C
5个回答

3

您似乎想要进行旋转而不是移位。您为什么不使用uint16类型而是使用[2]byte

无论如何,如果您真的想要使用[2]byte,那么这个方法更简单且不需要分支:

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
}

如果你想在任意数量的位上执行这样的操作,可以使用math/big


谢谢,Dave C!是的,我在文档中找到了关于uint16的更多信息。有些困惑。而且你的函数比我的更漂亮。我的糟糕英语没有帮助我,我是说rotate而不是shift。抱歉。 - user4611478

3

一种向左移位1位的解决方案。

func shiftBytesLeft(a []byte) (dst []byte) {
    n := len(a)
    dst = make([]byte, n)
    for i := 0; i < n-1; i++ {
        dst[i] = a[i] << 1
        dst[i] = (dst[i] & 0xfe) | (a[i+1] >> 7)
    }
    dst[n-1] = a[n-1] << 1
    return dst
}

2

这里是一个可以进行左移和右移的实现:

// ShiftLeft performs a left bit shift operation on the provided bytes.
// If the bits count is negative, a right bit shift is performed.
func ShiftLeft(data []byte, bits int) {
    n := len(data)
    if bits < 0 {
        bits = -bits
        for i := n - 1; i > 0; i-- {
            data[i] = data[i]>>bits | data[i-1]<<(8-bits)
        }
        data[0] >>= bits
    } else {
        for i := 0; i < n-1; i++ {
            data[i] = data[i]<<bits | data[i+1]>>(8-bits)
        }
        data[n-1] <<= bits
    }
}

1

是的!我找到了一个解决方案。

package main

import (
    "fmt"
)

type Byte [2]byte

//shift left
func SL(b Byte) Byte {
    if b[0]&0x80 == 0x80 {
        b[0] <<= 1
        if b[1]&0x80 == 0x80 {
            b[0] ^= 1
            b[1] <<= 1
        } else {
            b[1] <<= 1
        }
        b[1] ^= 0x01
    } else {
        b[0] <<= 1
        if b[1]&0x80 == 0x80 {
            b[0] ^= 1
            b[1] <<= 1
        } else {
            b[1] <<= 1
        }
    }
    return b
}

func main() {
    //var b Byte
    b := Byte{0x23, 0x86}
    fmt.Printf("old byte %#08b %#08b\n", b[0], b[1]) // 00100011 10000110
    c := SL(b)
    fmt.Printf("new byte %#08b %#08b", c[0], c[1]) // 01000111 00001100
}

1

将多个位左移,扩展qin的答案:

func shiftBytesLeft(a []byte, byBits int) (dst []byte) {
    n := len(a)
    dst = make([]byte, n)
    for i := 0; i < n-1; i++ {
        dst[i] = a[i] << byBits
        dst[i] = (dst[i] & (0xff - byte(byBits))) | (a[i+1] >> (8 - byte(byBits)))
    }
    dst[n-1] = a[n-1] << byBits
    return dst
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接