doutuo7156 2015-02-22 14:51 采纳率: 100%
浏览 57
已采纳

执行:将符文(字符串)转换为二进制的字符串表示形式

This is just in case someone else is learning Golang and is wondering how to convert from a string to a string representation in binary.

Long story short, I have been looking at the standard library without being able to find the right call. So I started with something similar to the following:

func RuneToBinary(r rune) string {
    var buf bytes.Buffer
    b := []int64{128, 64, 32, 16, 8, 4, 2, 1}
    v := int64(r)
    for i := 0; i < len(b); i++ {
        t := v-b[i]
        if t >= 0 {
           fmt.Fprintf(&buf, "1")
           v = t
        } else {
           fmt.Fprintf(&buf, "0")
        }
    }

    return buf.String()
}

This is all well and dandy, but after a couple of days looking around I found that I should have been using the fmt package instead and just format the rune with %b%:

var r rune
fmt.Printf("input: %b ", r)

Is there a better way to do this?

Thanks

  • 写回答

1条回答 默认 最新

  • doudanma9706 2015-02-22 15:14
    关注

    Standard library support

    fmt.Printf("%b", r) - this solution is already very compact and easy to write and understand. If you need the result as a string, you can use the analog Sprintf() function:

    s := fmt.Sprintf("%b", r)
    

    You can also use the strconv.FormatInt() function which takes a number of type int64 (so you first have to convert your rune) and a base where you can pass 2 to get the result in binary representation:

    s := strconv.FormatInt(int64(r), 2)
    

    Note that in Go rune is just an alias for int32, the 2 types are one and the same (just you may refer to it by 2 names).

    Doing it manually ("Simple but Naive"):

    If you'd want to do it "manually", there is a much simpler solution than your original. You can test the lowest bit with r & 0x01 == 0 and shift all bits with r >>= 1. Just "loop" over all bits and append either "1" or "0" depending on the bit:

    Note this is just for demonstration, it is nowhere near optimal regarding performance (generates "redundant" strings):

    func RuneToBin(r rune) (s string) {
        if r == 0 {
            return "0"
        }
        for digits := []string{"0", "1"}; r > 0; r >>= 1 {
            s = digits[r&1] + s
        }
        return
    }
    

    Note: negative numbers are not handled by the function. If you also want to handle negative numbers, you can first check it and proceed with the positive value of it and start the return value with a minus '-' sign. This also applies the other manual solution below.

    Manual Performance-wise solution:

    For a fast solution we shouldn't append strings. Since strings in Go are just byte slices encoded using UTF-8, appending a digit is just appending the byte value of the rune '0' or '1' which is just one byte (not multi). So we can allocate a big enough buffer/array (rune is 32 bits so max 32 binary digits), and fill it backwards so we won't even have to reverse it at the end. And return the used part of the array converted to string at the end. Note that I don't even call the built-in append function to append the binary digits, I just set the respective element of the array in which I build the result:

    func RuneToBinFast(r rune) string {
        if r == 0 {
            return "0"
        }
        b, i := [32]byte{}, 31
        for ; r > 0; r, i = r>>1, i-1 {
            if r&1 == 0 {
                b[i] = '0'
            } else {
                b[i] = '1'
            }
        }
        return string(b[i+1:])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀