dtttlua7165 2016-09-06 18:31
浏览 467
已采纳

定义一个不带hex.DecodeString的[] byte

I'm working with a HID driver, and this driver reads onto a []byte buffer one of a few different reports. When I use hex.EncodeToString(buffer), it will return a string looking like either 0000 or 0100 or 0200, etc. I want to check, using a switch, against the input from the HID device, and so I want to predefine these possibilities, up outside the main(), how should I proceed?

I've tried these possibilities:

var LEFT []byte = []byte('0000')
// or
var LEFT []byte = `0000`
// or 
var LEFT []byte = '0000'
// or
var LEFT []byte = '\x00\x00' // from the %q Printf verb

The alternative is that I call hex.DecodeString("0000") inside the main() function.

Edit

A note on the solution offered, the EncodeToString hex 0000 or 0100 is not four bytes but rather two:

"\x01" == "01" == '1'

so I can use, in order to get 0100, or 0200, as suggested:

var LEFT []byte{1,0}
// or 
var LEFT []byte("\x01\x00")
  • 写回答

3条回答 默认 最新

  • douzong7283 2016-09-06 18:37
    关注

    Use the following:

    var (
        left = []byte{0, 0}
        right = []byte{1, 0}
        // ... and so on
    )
    

    If you want to write it on hex:

    var (
        left = []byte{0x00, 0x00}
        right = []byte{0x01, 0x00}
        // ... and so on
    )
    

    You can also convert a string to a []byte:

    var (
        left = []byte("\x00\x00")
        right = []byte("\x01\x00")
    )
    

    Use these variables in a switch statement like this:

    switch {
    case bytes.Equal(v, left):
        fmt.Println("left")
    case bytes.Equal(v, right): 
        fmt.Println("right"
    }
    

    It looks like you are working with 2 byte numbers encoded in little-endian format. If so, you can decode the bytes to an integer:

    const (
        left = 0
        right = 1
    )
    
    switch binary.LittleEndian.Uint16(byteSlice) {
    case left:
        fmt.Println("left")
    case right:
        fmt.Println("right")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算