我试图定义一个用于在8位单字节记录上保留位标志的公共结构,以避免使用逐位操作使我的代码混乱。这就是我所拥有的:
var http = require("http");
http.createServer(function(request,response){
response.writeHead(200, {"content-type":"text/html"});
response.write("hello world");
response.end();
}).listen(8080);
console.log("server is running....");
这是输出:
typedef struct
{
uint8_t v1:1; // Bit 7
uint8_t v2:1; // Bit 6
uint8_t v3:1; // Bit 5
uint8_t v4:1; // Bit 4
uint8_t v5:1; // Bit 3
uint8_t v6:1; // Bit 2
uint8_t v7:1; // Bit 1
uint8_t v8:1; // Bit 0
} record8x1_t;
typedef struct
{
uint8_t v1:2; // Bits 7-6
uint8_t v2:2; // Bits 5-4
uint8_t v3:2; // Bits 3-2
uint8_t v4:2; // Bits 1-0
} record8x2_t;
typedef struct
{
uint8_t v1:4; // Bits 7-4
uint8_t v2:4; // Bits 3-0
} record8x4_t;
typedef union
{
uint8_t value;
record8x1_t s1;
record8x2_t s2;
record8x4_t s4;
} record8_t;
record8_t eight_bits;
eight_bits.value = 0x0D;
std::cout << "eight_bits.s1.v1 = " << (int)eight_bits.s1.v1 << std::endl;
std::cout << "eight_bits.s1.v2 = " << (int)eight_bits.s1.v2 << std::endl;
std::cout << "eight_bits.s1.v3 = " << (int)eight_bits.s1.v3 << std::endl;
std::cout << "eight_bits.s1.v4 = " << (int)eight_bits.s1.v4 << std::endl;
std::cout << "eight_bits.s1.v5 = " << (int)eight_bits.s1.v5 << std::endl;
std::cout << "eight_bits.s1.v6 = " << (int)eight_bits.s1.v6 << std::endl;
std::cout << "eight_bits.s1.v7 = " << (int)eight_bits.s1.v7 << std::endl;
std::cout << "eight_bits.s1.v8 = " << (int)eight_bits.s1.v8 << std::endl;
std::cout << std::endl;
std::cout << "eight_bits.s2.v1 = " << (int)eight_bits.s2.v1 << std::endl;
std::cout << "eight_bits.s2.v2 = " << (int)eight_bits.s2.v2 << std::endl;
std::cout << "eight_bits.s2.v3 = " << (int)eight_bits.s2.v3 << std::endl;
std::cout << "eight_bits.s2.v4 = " << (int)eight_bits.s2.v4 << std::endl;
std::cout << std::endl;
std::cout << "eight_bits.s4.v1 = " << (int)eight_bits.s4.v1 << std::endl;
std::cout << "eight_bits.s4.v2 = " << (int)eight_bits.s4.v2 << std::endl;
我期待这些位从左到右,从高到低依次为 00001101 ,而不是相反的 1011000 。我在 CentOS 6.8 主机上使用 g ++(GCC)4.4.7 20120313(Red Hat 4.4.7-17)。
问题:这是一个大/小端的东西还是编译器依赖的?是否有某种 pragma 设置来解决这个问题?
这是我期待的输出:
eight_bits.s1.v1 = 1
eight_bits.s1.v2 = 0
eight_bits.s1.v3 = 1
eight_bits.s1.v4 = 1
eight_bits.s1.v5 = 0
eight_bits.s1.v6 = 0
eight_bits.s1.v7 = 0
eight_bits.s1.v8 = 0
eight_bits.s2.v1 = 1
eight_bits.s2.v2 = 3
eight_bits.s2.v3 = 0
eight_bits.s2.v4 = 0
eight_bits.s4.v1 = 13
eight_bits.s4.v2 = 0