【发布时间】:2018-07-16 17:26:06
【问题描述】:
我似乎无法将 1 和 0 的位串转换为字节数组。
这是我目前的代码:
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)
}
我显然遗漏了一些东西,但我似乎无法将这种大小的位字符串转换为字节数组。
edit我通过了第一个错误:
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)
}
但它没有输出我期望的字节数组的样子:
[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]
我希望它是十六进制的?这不是字节数组在 golang 中的样子吗?
【问题讨论】:
-
您可能需要使用大整数:golang.org/pkg/math/big
-
将字符串 8bits 乘以 8bits 组成一个字节(uint8)。
-
我刚刚点击了那个链接。我会看看那些的大小。是的,我想我应该一个字节一个字节地做。
-
您希望将每个 8 位序列存储为一个字节,将整数存储为可以用作数字的东西,还是每个位存储一个字节?您的示例代码听起来像是一个很大的数字,需要
math/big -
对不起@Marc,这还不清楚。我想要一个字节数组。