qt初入门4:大小端(小端转成大端code)

判断电脑大小端,并进行小端转换成大端。

bool CommonInterface::IsBigEndian()
{
    short a = 0x1234;
    char b = *(char*)&a;
    if (0x12 == b) //高位存储在低地址处  是大端
    {
        return true;
    }
    return false; //否则   高位存储在高地址位  小端模式
}

unsigned int CommonInterface::int_host_to_network(unsigned int number)
{
    bool flag = IsBigEndian();
    if (flag) //大端模式  不用处理
    {
        return number;
    }

    unsigned int data = number;
    unsigned char* abyte0 = (unsigned char*)&data;
    // 小端模式
    if (!flag) //如果电脑是小端模式  需要处理成大端模式
    {
        abyte0[0] = (unsigned char)((0xff000000 & number) >> 24);
        abyte0[1] = (unsigned char)((0x00ff0000 & number) >> 16);
        abyte0[2] = (unsigned char)((0x0000ff00 & number) >> 8);
        abyte0[3] = (unsigned char)(0x000000ff & number);
    }

    return data;
}

unsigned short CommonInterface::short_host_to_network(unsigned short number)
{
    bool flag = IsBigEndian();
    if (flag) //大端模式  不用处理
    {
        return number;
    }
    unsigned short data = number;
    unsigned char* abyte0 = (unsigned char*)&data;
    // 小端模式 //需要进行处理
    if (!flag)
    {
        abyte0[0] = (unsigned char)((0xff00 & number) >> 8);
        abyte0[1] = (unsigned char)(0x00ff & number);
    }
    return data;
}

你可能感兴趣的:(qt相关问题及学习,qt,开发语言)