go - bool 数组到字节数组

标签 go

我有将字节数组转换为表示 0 和 1 的 bool 数组的函数:

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
}

一个函数怎么看起来恰恰相反,意味着将 bool 数组转换为字节数组?

编辑:这个 playground 提供了更多关于我的字节数组的细节:https://play.golang.org/p/tEDcZv-t_0Q

ba := []byte{123, 255}

最佳答案

例如,boolsToBytesbytesToBools 的逆(完全相反),

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)
}

Playground :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))
}

Playground :https://play.golang.org/p/L9VsTtbkQZW

输出:

[true true true true]
[true true true true]
[true true true true]

关于go - bool 数组到字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53924984/

相关文章:

pointers - 戈朗 Cgo : panic: runtime error: cgo argument has Go pointer to Go pointer

go - 如何处理 bytes.Buffer 流中的 io.EOF?

go - 如何在 Go 中使用 reflect 获取 map 接口(interface)的值?

go - os.Getenv 有多贵?

go - 从字符串转换为整数(如果不成功则抛出错误)

go - 测试信号量实现时出错

file - 在 Go 中读取/写入文件的正确方法

使用 1.5.x 进行交叉编译 - 输出文件被覆盖

go - 通过 Golang 记录器写入日志

windows - Windows 上的 golang cgo 退出状态 2