dongma7796 2018-09-04 18:44
浏览 43
已采纳

二进制字符串到十六进制

I have a string with 128 values like 011100010.... I would like to convert this to a hex string. What I found was the other direction:

func partHexToBin(s string) string {
    ui, err := strconv.ParseUint(s, 16, 8)
    if err != nil {
        return ""
    }

    return fmt.Sprintf("%016b", ui)
}
  • 写回答

1条回答 默认 最新

  • dongren1977 2018-09-04 19:02
    关注

    You can do the exact same thing the other way, since ParseInt allows you to pass the base of the number (decimal, hexadecimal, binary, etc.)

    ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

    Then, once you changed the base in the ParseUint call from 16 to 2, you'll need to change your Sprintf call to print the number to hexadecimal, using the %x format flag.

    Please note however that using ParseUint followed by a call to Sprintf might not be the most performant solution.

    See this example:

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func parseBinToHex(s string) string {
        ui, err := strconv.ParseUint(s, 2, 64)
        if err != nil {
            return "error"
        }
    
        return fmt.Sprintf("%x", ui)
    }
    
    func main() {
        fmt.Println(parseBinToHex("11101"))
    }
    

    Output gives

    1d

    Feel free to play around with it on the Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障