dqusbxh44823 2016-10-21 17:39
浏览 255
已采纳

读取二进制文件时切换字节序

Trying to parse a file with binary records. The first byte of each record tells you the endianness of each record. Theoretically the endianness can change between records. How can I switch from binary.BigEndian to binary.LittleEndian. I'm a total Golang newbie...

package main

import (
    "fmt"
    //"time"
    "reflect"
    "encoding/binary"
)

func main() {
    var b byte = 0xe2
    e := binary.BigEndian
    switch b {
    case 0xe2:
        e = binary.BigEndian
    default:
        e = binary.LittleEndian
    }
    fmt.Println(reflect.TypeOf(e))
}

tmp/sandbox356311773/main.go:17: cannot use binary.LittleEndian (type binary.littleEndian) as type binary.bigEndian in assignment

  • 写回答

1条回答 默认 最新

  • dongzhan1492 2016-10-21 17:41
    关注

    binary.BigEndian and binary.LittleEndian are are both implementations of binary.ByteOrder. Declare e as type binary.ByteOrder, and you can switch back and forth between the two implementations.

    https://play.golang.org/p/GzL_2q5wvn

    var b byte = 0xe2
    var e binary.ByteOrder
    switch b {
    case 0xe2:
        e = binary.BigEndian
    default:
        e = binary.LittleEndian
    }
    fmt.Println(reflect.TypeOf(e))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大