加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang(Go语言) byte/[]byte 与 二进制形式字符串 互转

发布时间:2020-12-16 18:26:39 所属栏目:大数据 来源:网络整理
导读:效果 把某个字节或字节数组转换成字符串01的形式,一个字节用8个”0”或”1”字符表示。比如: byte(3) – “00000011” []byte{1,2,3} – “[00000001 00000010 00000011]” “[00000011 10000000]” – []byte{0x3,0x80} 开源库 biu 实际上我已经将其封装

效果

把某个字节或字节数组转换成字符串01的形式,一个字节用8个”0”或”1”字符表示。比如:
byte(3) –> “00000011”
[]byte{1,2,3} –> “[00000001 00000010 00000011]”
“[00000011 10000000]” –> []byte{0x3,0x80}

开源库 biu

实际上我已经将其封装到一个开源库了(biu),其中的一个功能就能达到上述效果:

//byte/[]byte -> string
bs := []byte{1, 2, 3}
s := biu.BytesToBinaryString(bs)
fmt.Println(s) //[00000001 00000010 00000011]
fmt.Println(biu.ByteToBinaryString(byte(3))) //00000011

//string -> []byte
s := "[00000011 10000000]"
bs := biu.BinaryStringToBytes(s)
fmt.Printf("%#vn",bs) //[]byte{0x3,0x80}

代码实现

const (
    zero  = byte('0')
    one   = byte('1')
    lsb   = byte('[') // left square brackets
    rsb   = byte(']') // right square brackets
    space = byte(' ')
)

var uint8arr [8]uint8

// ErrBadStringFormat represents a error of input string's format is illegal .
var ErrBadStringFormat = errors.New("bad string format")

// ErrEmptyString represents a error of empty input string.
var ErrEmptyString = errors.New("empty string")


func init() {
    uint8arr[0] = 128
    uint8arr[1] = 64
    uint8arr[2] = 32
    uint8arr[3] = 16
    uint8arr[4] = 8
    uint8arr[5] = 4
    uint8arr[6] = 2
    uint8arr[7] = 1
}

// append bytes of string in binary format.
func appendBinaryString(bs []byte,b byte) []byte {
    var a byte
    for i := 0; i < 8; i++ {
        a = b
        b <<= 1
        b >>= 1
        switch a {
        case b:
            bs = append(bs,zero)
        default:
            bs = append(bs,one)
        }
        b <<= 1
    }
    return bs
}


// ByteToBinaryString get the string in binary format of a byte or uint8.
func ByteToBinaryString(b byte) string {
    buf := make([]byte, 0, 8)
    buf = appendBinaryString(buf,b)
    return string(buf)
}

// BytesToBinaryString get the string in binary format of a []byte or []int8.
func BytesToBinaryString(bs []byte) string {
    l := len(bs)
    bl := l*8 + l + 1
    buf := make([]byte,bl)
    buf = append(buf,lsb)
    for _,b := range bs {
        buf = appendBinaryString(buf,b)
        buf = append(buf,space)
    }
    buf[bl-1] = rsb
    return string(buf)
}

// regex for delete useless string which is going to be in binary format.
var rbDel = regexp.MustCompile(`[^01]`)

// BinaryStringToBytes get the binary bytes according to the
// input string which is in binary format.
func BinaryStringToBytes(s string) (bs []byte) {
    if len(s) == 0 {
        panic(ErrEmptyString)
    }

    s = rbDel.ReplaceAllString(s,"")
    l := len(s)
    if l == 0 {
        panic(ErrBadStringFormat)
    }

    mo := l % 8
    l /= 8
    if mo != 0 {
        l++
    }
    bs = make([]byte,l)
    mo = 8 - mo
    var n uint8
    for i,b := range []byte(s) {
        m := (i + mo) % 8
        switch b {
        case one:
            n += uint8arr[m]
        }
        if m == 7 {
            bs = append(bs,n)
            n = 0
        }
    }
    return
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读