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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c