亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

布爾數組到字節數組

布爾數組到字節數組

Go
拉風的咖菲貓 2023-05-22 16:57:56
我有將字節數組轉換為表示 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_0Qba := []byte{123, 255}
查看完整描述

1 回答

?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

例如,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]


查看完整回答
反對 回復 2023-05-22
  • 1 回答
  • 0 關注
  • 232 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號