go - 布尔数组到字节数组
问题描述
我具有将字节数组转换为表示 0 和 1 的布尔数组的功能:
func byteArrayToBoolArray(ba []byte) []bool {
var s []bool
for _, b := range ba {
for _, c := range strconv.FormatUint(uint64(by), 2) {
s = append(s, c == []rune("1")[0])
}
}
return s
}
一个函数看起来如何完全相反,这意味着将布尔数组转换为字节数组?
编辑:这个游乐场提供了我的字节数组的更多细节:https: //play.golang.org/p/tEDcZv-t_0Q
ba := []byte{123, 255}
解决方案
例如,boolsToBytes
, 的倒数(正好相反)bytesToBools
,
package main
import (
"fmt"
)
func boolsToBytes(t []bool) []byte {
b := make([]byte, (len(t)+7)/8)
for i, x := range t {
if x {
b[i/8] |= 0x80 >> uint(i%8)
}
}
return b
}
func bytesToBools(b []byte) []bool {
t := make([]bool, 8*len(b))
for i, x := range b {
for j := 0; j < 8; j++ {
if (x<<uint(j))&0x80 == 0x80 {
t[8*i+j] = true
}
}
}
return t
}
func main() {
b := []byte{123, 255}
fmt.Println(b)
t := bytesToBools(b)
fmt.Printf("%t\n", t)
b = boolsToBytes(t)
fmt.Println(b)
}
游乐场: https: //play.golang.org/p/IguJ_4cZKtA
输出:
[123 255]
[false true true true true false true true true true true true true true true true]
[123 255]
该问题提供了一个函数并要求一个反函数(完全相反)。
问题函数算法存在缺陷,多个输入映射到相同的函数值。因此,不存在唯一逆。
package main
import (
"fmt"
"strconv"
)
func byteArrayToBoolArray(ba []byte) []bool {
var s []bool
for _, b := range ba {
for _, c := range strconv.FormatUint(uint64(b), 2) {
s = append(s, c == []rune("1")[0])
}
}
return s
}
func main() {
ba1 := []byte{0xF}
fmt.Println(byteArrayToBoolArray(ba1))
ba2 := []byte{0x3, 0x3}
fmt.Println(byteArrayToBoolArray(ba2))
ba3 := []byte{0x1, 0x1, 0x1, 0x1}
fmt.Println(byteArrayToBoolArray(ba3))
}
游乐场: https: //play.golang.org/p/L9VsTtbkQZW
输出:
[true true true true]
[true true true true]
[true true true true]
推荐阅读
- shell - 如何使用 sed 和 cut 在文件中行的特定位置查找和替换值
- angular - 如何在本地存储中设置 Angular 标头值?
- html - 如何使用 Bootstrap 强制呈现表单?
- bash - 用于删除以文件中列出的文本开头的文件的脚本
- php - cURL 错误 18:传输已关闭,剩余未完成的读取数据
- powershell - 如何正确使用“压缩存档”?错误消息一直说“路径不存在或不是有效的文件系统路径”
- python - “?”是什么意思?在张量流中?
- javascript - 在 netlify 上部署反应应用程序后 HTTP GET 响应 304 状态错误
- python - 合并数组和绘图
- maven - 无法使用 Maven jar 插件添加资源