dongxuandong2045 2019-02-21 14:21
浏览 395
已采纳

Golang:从一个字节解析位值

I need to parse a network packet which consists of two bytes: first one consists of 8 bits that set certain flags depending on their order (for instance) and the second one is uint8 (which is simple)

  • 1 - online
  • 0 - not active
  • 1 - isPretty
  • 1 - isHandsome
  • 0 - bald
  • 0 - deaf
  • 0 - mute
  • 0 - blind

How do I parse it from a byte primitive?

  • 写回答

1条回答 默认 最新

  • doupian9490 2019-02-21 14:34
    关注

    Some useful Go standard library packages for dealing with binary:

    For extracting single bits from a byte, you ought to use bitwise operators - |, & and >>.

    For example:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        v := byte(0xB2)
        if (v >> 4) & 1 == 1 {
            fmt.Println("bit 4 (counting from 0) is set")
        }
    }
    

    This checks bit 4 (with bit 0 being the lowest bit in the byte) by shifting the byte value 4 positions to the right and AND-ing with 1. You can check the other bits in your flag value similarly. Feel free to write a function that replaces the 4 in the sample above with an argument N to check bit number N.

    You can find more examples in other SO answers like this one or the ones @icza linked to in a comment.

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格