dongzuo7166 2019-07-18 19:05
浏览 433

将字节数组转换为int64 golang数组

I came across a situation where I want to convert an array of byte to array of int64 and I am trying to do the below

func covertToInt64(message []byte) []int64{
    rbuf := bytes.NewBuffer(message)
        arr := []int64{}
        e := binary.Read(rbuf, binary.LittleEndian, &arr)
        if e != nil {

        }
    return arr
    }

The above returns an empty arr but when I convert []byte to a string as below

msg:=string(message)

msg have the value "[1,2]"

May I know a better and correct way to do this in Go?

  • 写回答

1条回答 默认 最新

  • dsewbh5588 2019-07-20 14:40
    关注

    The question is what is exactly that you want? If the message is byte values from 0 to 0xFF, and you simply want to cast each member of the slice into int64, then the answer is:

    ints := make([]int64, len(message))
    for index, b := range message {
        ints[index] = int64(b)
    }
    

    If the the message is the binary data, representing int64 values, then the solution is a bit more complicated than that. Because int64 is 8 bytes long each, thus to be able to convert a slice of bytes, the length of the message must be divisible by eight without any remainder at it's best. We're dropping other cases here.

    So, then the answer is:

    ml := len(message)
    il := ml/8
    
    if ml%8 != 0 {
        // there's more than il*8 bytes, but not 
        // enough to make il+1 int64 values
        // error out here, if needed
    }
    
    ints := make([]int64, il)
    err := binary.Read(bytes.NewReader(message), ints)
    

    The thing is that when you call binary.Read you need to know the size of the destination value in advance. And the reading fails because: destination length is zero, and in addition the source length is not enough to read even a single one int64 value.

    I guess the second situation is a bit more complicated and what you actually wanted can be solved with the first scenario.

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题