位域和字节相互转化

struct Byte 
{
    unsigned int bit0 : 1;
    unsigned int bit1 : 1;
    unsigned int bit2 : 1;
    unsigned int bit3 : 1;
    unsigned int bit4 : 1;
    unsigned int bit5 : 1;
    unsigned int bit6 : 1;
    unsigned int bit7 : 1;
};

struct Byte byteToBits(unsigned char byte)
{
    struct Byte b;
    b.bit0 = byte & 0x01;
    b.bit1 = (byte & 0x02) >> 1;
    b.bit2 = (byte & 0x04) >> 2;
    b.bit3 = (byte & 0x08) >> 3;
    b.bit4 = (byte & 0x10) >> 4;
    b.bit5 = (byte & 0x20) >> 5;
    b.bit6 = (byte & 0x40) >> 6;
    b.bit7 = (byte & 0x80) >> 7;
    return b;
}

unsigned char  BitFieldToByte(struct Byte b)
{
    // 将位域转为字节
    unsigned char byte = b.bit7 << 7 | b.bit6 << 6 | b.bit5 << 5 | b.bit4 << 4
        | b.bit3 << 3 | b.bit2 << 2 | b.bit1 << 1 | b.bit0;

    return byte;
}


//eg
// 访问每个位的值
//printf("bit0 = %d\n", b.bit0);
//printf("bit1 = %d\n", b.bit1);
//printf("bit2 = %d\n", b.bit2);
//printf("bit3 = %d\n", b.bit3);
//printf("bit4 = %d\n", b.bit4);
//printf("bit5 = %d\n", b.bit5);
//printf("bit6 = %d\n", b.bit6);
//printf("bit7 = %d\n", b.bit7);

//字节转int

// int转字节数组
void IntToByteArray(int n, unsigned char *byteArray)
{
    byteArray[0] = (unsigned char)(n & 0xff);
    byteArray[1] = (unsigned char)((n >> 8) & 0xff);
    byteArray[2] = (unsigned char)((n >> 16) & 0xff);
    byteArray[3] = (unsigned char)((n >> 24) & 0xff);
}

//int 转字节

int byteArrayToInt(unsigned char* byteArray)
{
    int result = 0;
    for (int i = 0; i < 4; ++i)
    {
        result += (byteArray[i] << (i * 8));
    }
    return result;
}

你可能感兴趣的:(位域和字节相互转化)