implementation-defined, / . , ( -) .
.
#include <iostream>
bool GetBit(uint32_t num, uint8_t pos)
{
return (num >> pos) & 0x1;
}
uint8_t GetByte(uint32_t num, uint8_t pos)
{
return (num >> pos) & 0xFF;
}
uint16_t GetShort(uint32_t num, uint8_t pos)
{
return (num >> pos) & 0xFFFF;
}
uint32_t SetBit(bool val, uint32_t &dest, uint8_t pos)
{
dest ^= (-val ^ dest) & (1 << pos);
return dest;
}
uint32_t SetByte(uint8_t val, uint32_t &dest, uint8_t pos)
{
dest &= ~(0xFF<<pos);
dest |= val<<pos;
return dest;
}
uint32_t SetShort(uint16_t val, uint32_t &dest, uint8_t pos)
{
dest &= ~(0xFFFF<<pos);
dest |= val<<pos;
return dest;
}
void PrintBin(uint32_t s, const char* pszComment)
{
std::cout << pszComment << ": " << std::endl;
for (size_t n = 0; n < sizeof(s) * 8; n++)
std::cout << GetBit(s, n) << ' ';
std::cout << std::endl;
}
int main()
{
uint32_t s = 4294967295;
PrintBin(s, "Start");
SetBit(false, s, 2);
PrintBin(s, "Set bit 2 to FALSE");
SetByte(0, s, 22);
PrintBin(s, "Set byte 22 to val 0");
SetByte(30, s, 22);
PrintBin(s, "Set byte 22 to val 30");
SetShort(0, s, 4);
PrintBin(s, "Set short 4 to val 0");
SetShort(65000, s, 4);
PrintBin(s, "Set short 4 to val 65000");
std::cout << "byte at 22 = " << (int)GetByte(s, 22) << std::endl;
std::cout << "short at 4 = " << (int)GetShort(s, 4) << std::endl;
}
:
Start:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Set bit 2 to FALSE:
1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Set byte 22 to val 0:
1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1
Set byte 22 to val 30:
1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 1
Set short 4 to val 0:
1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 0 0 0 1 1
Set short 4 to val 65000:
1 1 0 1 0 0 0 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 1
byte at 22 = 30
short at 4 = 65000
#DEFINE .