dongyuan3094 2014-08-20 15:39
浏览 14
已采纳

将字节数组的一部分隐蔽到uint16的最简单方法

if I byte array:

byte_array := []byte("klm,\x15\xf1
")

I would like to the byte \x15 and \xf1 to uint16 in LittleEndian order. What is the easiest way of doing it?

Tried the following:

var new_uint uint16
bff := bytes.newRead(byte_array[4:5])
err = binary.Read(buff, binary.LittleEndian, &new_uint)

but I keep getting nothing, and this is relatively complicated, is there an easier way of doing it?

Thanks...

  • 写回答

1条回答 默认 最新

  • drcmue4619 2014-08-20 15:42
    关注

    You have 2 options, using binary.LittleEndian like you already did, a shorter way is:

    u16 := binary.LittleEndian.Uint16(byte_array[4:])
    

    Or if you like to live dangerously, you can use unsafe:

    // This will return the wrong number on a BE system,
    // also unsafe is not available on GAE.
    u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))
    

    <kbd>playground</kbd>

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

报告相同问题?

悬赏问题

  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效