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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序