doukao8851 2018-02-06 15:33
浏览 83
已采纳

将位串转换为字节数组

I can't seem to convert a bit string of 1s and 0s to a byte array.

Here is the code I have so far:

package main

import (
    "strconv"
    "encoding/binary"
    "fmt"
)

func main() {
    /* goal: convert a bit string (ex "10110110") to a byte array */
    bitString := "00000000000000000000000100111000100001100000000000000000000000000000000000000000000000000000000000000000000000000000000000000011"

    bitNum, err := strconv.ParseUint(bitString, 2, 128) // turn my 128-bit bitstring into an int

    if err != nil {
        panic(err) // currently panics with "value out of range"
    }

    // convert my integer to a byte array
    // code from https://stackoverflow.com/questions/16888357/convert-an-integer-to-a-byte-array
    bs := make([]byte, 128)                   // allocate memory for my byte array
    binary.LittleEndian.PutUint64(bs, bitNum) // convert my bitnum to a byte array
    fmt.Println(bs)

}

I am clearly missing something, but I can't seem to convert a bit string of that size to a byte array.

edit I got passed the first error with this:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    /* goal: convert a bit string (ex "10110110") to a byte array */
    bitString := "00000000000000000000000100111000100001100000000000000000000000000000000000000000000000000000000000000000000000000000000000000011"

    myBytes := make([]byte, 16)
    for len(bitString) > 7 {
        currentByteStr := bitString[:8]
        bitString = bitString[8:]
        currentByteInt, _ := strconv.ParseUint(currentByteStr, 2, 8)
        currentByte := byte(currentByteInt)
        myBytes = append(myBytes, currentByte)
    }

    fmt.Println(myBytes)

}

but it doesn't output what I would expect a byte array to look like:

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 56 134 0 0 0 0 0 0 0 0 0 0 3]

I would have expected it to be hex? is that not what a byte array looks like in golang?

  • 写回答

3条回答 默认 最新

  • dongzongzi0379 2018-02-06 16:29
    关注

    I would opt for making a new type, butString, with methods for converting to a []byte and []string (for hex if you like). This should also guard against an input string not evenly divisible by 8.

    package main
    
    import (
        "encoding/hex"
        "fmt"
        "strconv"
    )
    
    type bitString string
    
    func (b bitString) AsByteSlice() []byte {
        var out []byte
        var str string
    
        for i := len(b); i > 0; i -= 8 {
            if i-8 < 0 {
                str = string(b[0:i])
            } else {
                str = string(b[i-8 : i])
            }
            v, err := strconv.ParseUint(str, 2, 8)
            if err != nil {
                panic(err)
            }
            out = append([]byte{byte(v)}, out...)
        }
        return out
    }
    
    func (b bitString) AsHexSlice() []string {
        var out []string
        byteSlice := b.AsByteSlice()
        for _, b := range byteSlice {
            out = append(out, "0x" + hex.EncodeToString([]byte{b}))
        }
        return out
    }
    
    func main() {
        x := bitString("00000000000000000000000100111000100001100000000000000000000000000000000000000000000000000000000000000000000000000000000000000011")
        fmt.Println(x.AsByteSlice())
        fmt.Println(x.AsHexSlice())
    }
    

    OUTPUT

    [64 0 1 56 134 0 0 0 0 0 0 0 0 0 0 3]
    [0x00 0x00 0x01 0x38 0x86 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x03]
    

    Playgroud

    If speed is a concern, then optimization can be achieved by allocating the slice with the appropriate capacity and tracking the index yourself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集