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

这里简单的工作代码左移一个字节的第一位


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?


子衿沉夜
浏览 290回答 3
3回答

慕桂英546537

您似乎想要旋转,而不是移动。您不使用uint16类型而不是 的任何特殊原因[2]byte?无论如何,如果你真的想要[2]byte,这更简单并且不会分支:func rol(v [2]byte) [2]byte {&nbsp; &nbsp; x := int(v[0])<<8 | int(v[1])&nbsp; &nbsp; x <<= 1&nbsp; &nbsp; v[0] = byte(x >> 8)&nbsp; &nbsp; v[1] = byte((x & 0xff) | x>>16)&nbsp; &nbsp; return v}如果你想对任意大量的位进行这样的操作,你可以使用math/big.

holdtom

左移 1 位的解决方案。func shiftBytesLeft(a []byte) (dst []byte) {&nbsp; &nbsp; n := len(a)&nbsp; &nbsp; dst = make([]byte, n)&nbsp; &nbsp; for i := 0; i < n-1; i++ {&nbsp; &nbsp; &nbsp; &nbsp; dst[i] = a[i] << 1&nbsp; &nbsp; &nbsp; &nbsp; dst[i] = (dst[i] & 0xfe) | (a[i+1] >> 7)&nbsp; &nbsp; }&nbsp; &nbsp; dst[n-1] = a[n-1] << 1&nbsp; &nbsp; return dst}

达令说

这是一个可以同时进行左移和右移的实现:// 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) {&nbsp; &nbsp; n := len(data)&nbsp; &nbsp; if bits < 0 {&nbsp; &nbsp; &nbsp; &nbsp; bits = -bits&nbsp; &nbsp; &nbsp; &nbsp; for i := n - 1; i > 0; i-- {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data[i] = data[i]>>bits | data[i-1]<<(8-bits)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; data[0] >>= bits&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < n-1; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data[i] = data[i]<<bits | data[i+1]>>(8-bits)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; data[n-1] <<= bits&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go