You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用#pragma pack后C++结构体仍有填充,如何实现3字节24位整数类型?

在Visual Studio 2019中实现3字节的24位整数结构体

问题根源

你碰到的sizeof(int24)返回4的情况,核心原因是如果结构体里用int作为位域的基础类型,哪怕开启了#pragma pack(push,1),int本身的4字节对齐属性会让编译器为结构体保留完整的4字节空间——位域无法突破基础类型的大小限制。

解决方案

要实现严格3字节的24位整数,你可以用三个独立的unsigned char成员(而非数组)结合#pragma pack(1)或VS专属的__declspec(packed)消除填充,同时重载必要运算符让结构体具备普通整数的操作特性:

代码实现

#pragma pack(push, 1)
struct int24 {
    // 按小端序存储24位整数,可根据需求调整为大端
    unsigned char lo;
    unsigned char mid;
    unsigned char hi;

    // 转换为int类型
    operator int() const {
        return (static_cast<int>(hi) << 16) | (static_cast<int>(mid) << 8) | lo;
    }

    // 从int赋值
    int24& operator=(int value) {
        lo = static_cast<unsigned char>(value & 0xFF);
        mid = static_cast<unsigned char>((value >> 8) & 0xFF);
        hi = static_cast<unsigned char>((value >> 16) & 0xFF);
        return *this;
    }

    // 重载加法运算符
    int24 operator+(const int24& other) const {
        int24 result;
        result = static_cast<int>(*this) + static_cast<int>(other);
        return result;
    }

    // 可根据需求继续重载-、*、/、比较运算符等
};
#pragma pack(pop)

验证大小

此时在VS2019中调用sizeof(int24)会返回3,完全符合需求。

补充写法

  • 如果偏好位域语法,也可以这样实现(效果一致):
    #pragma pack(push, 1)
    struct int24 {
        unsigned char lo : 8;
        unsigned char mid : 8;
        unsigned char hi : 8;
    
        // 同样需要重载运算符...
    };
    #pragma pack(pop)
    
  • 也可以用__declspec(packed)直接修饰结构体替代#pragma pack:
    struct __declspec(packed) int24 {
        unsigned char lo;
        unsigned char mid;
        unsigned char hi;
        // 运算符重载...
    };
    

内容的提问来源于stack exchange,提问作者David Stuckey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 05:48:20