dongwujie7477
2015-04-04 04:28
浏览 110
已采纳

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

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
", 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!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongying7847 2015-04-04 07:15
    已采纳

    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.

    打赏 评论
  • dousenjue3214 2015-04-04 04:55

    Yep! I found a solution.

    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
    ", b[0], b[1]) // 00100011 10000110
        c := SL(b)
        fmt.Printf("new byte %#08b %#08b", c[0], c[1]) // 01000111 00001100
    }
    
    打赏 评论
  • drh19790711 2019-02-13 02:09

    A solution to shift left 1 bit.

    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
    }
    
    打赏 评论

相关推荐 更多相似问题