duaner1634 2013-10-23 23:00
浏览 39
已采纳

Go中无符号整数的二进制表示形式

Is there a built-in function to convert a uint to a slice of binary integers {0,1} ?

>> convert_to_binary(2)
[1, 0]
  • 写回答

1条回答 默认 最新

  • dongxingji3882 2013-10-23 23:42
    关注

    I am not aware of such a function, however you can use strconv.FormatUint for that purpose.

    Example (on play):

    func Bits(i uint64) []byte {
        bits := []byte{}
    
        for _, b := range strconv.FormatUint(i, 2) {
             bits = append(bits, byte(b - rune('0')))
        }
    
        return bits
    }
    

    FormatUint will return the string representation of the given uint to a base, in this case 2, so we're encoding it in binary. So the returned string for i=2 looks like this: "10". In bytes this is [49 48] as 1 is 49 and 0 is 48 in ASCII and Unicode. So we just need to iterate over the string, subtracting 48 from each rune (unicode character) and converting it to a byte.

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

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口