布尔数组到字节数组

我有将字节数组转换为表示 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 数组转换为字节数组?


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


ba := []byte{123, 255}


拉风的咖菲猫
浏览 153回答 1
1回答

慕容3067478

例如,boolsToBytes的倒数(恰好相反)bytesToBools,package mainimport (&nbsp; &nbsp; "fmt")func boolsToBytes(t []bool) []byte {&nbsp; &nbsp; b := make([]byte, (len(t)+7)/8)&nbsp; &nbsp; for i, x := range t {&nbsp; &nbsp; &nbsp; &nbsp; if x {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b[i/8] |= 0x80 >> uint(i%8)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return b}func bytesToBools(b []byte) []bool {&nbsp; &nbsp; t := make([]bool, 8*len(b))&nbsp; &nbsp; for i, x := range b {&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < 8; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (x<<uint(j))&0x80 == 0x80 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t[8*i+j] = true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return t}func main() {&nbsp; &nbsp; b := []byte{123, 255}&nbsp; &nbsp; fmt.Println(b)&nbsp; &nbsp; t := bytesToBools(b)&nbsp; &nbsp; fmt.Printf("%t\n", t)&nbsp; &nbsp; b = boolsToBytes(t)&nbsp; &nbsp; 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 mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strconv")func byteArrayToBoolArray(ba []byte) []bool {&nbsp; &nbsp; var s []bool&nbsp; &nbsp; for _, b := range ba {&nbsp; &nbsp; &nbsp; &nbsp; for _, c := range strconv.FormatUint(uint64(b), 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s = append(s, c == []rune("1")[0])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return s}func main() {&nbsp; &nbsp; ba1 := []byte{0xF}&nbsp; &nbsp; fmt.Println(byteArrayToBoolArray(ba1))&nbsp; &nbsp; ba2 := []byte{0x3, 0x3}&nbsp; &nbsp; fmt.Println(byteArrayToBoolArray(ba2))&nbsp; &nbsp; ba3 := []byte{0x1, 0x1, 0x1, 0x1}&nbsp; &nbsp; fmt.Println(byteArrayToBoolArray(ba3))}游乐场:https://play.golang.org/p/L9VsTtbkQZW输出:[true true true true][true true true true][true true true true]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go