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

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

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 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误