我在 c11 中编写一个 CHIP-8 解释器是为了好玩,我认为使用匿名结构解码操作码会很酷。
理想情况下,如果我有操作码,我会有一个类型opcode_t code = {.bits = 0xABCD}
它应该具有以下属性:
code.I == 0xA
code.X == 0xB
code.Y == 0xC
code.J == 0xD
code.NNN == 0xBCD
code.KK == 0xCD
我想出的结构是:
typedef union
{
uint16_t bits : 16;
struct
{
uint8_t I : 4;
union
{
uint16_t NNN : 12;
struct
{
uint8_t X : 4;
union
{
uint8_t KK : 8;
struct
{
uint8_t Y : 4;
uint8_t J : 4;
};
};
};
};
};
} opcode_t;
但是,当我运行以下代码来测试我的结构时
opcode_t test_opcode = { .bits = 0xABCD };
printf(
"I = %x, X = %x, Y = %x, J = %x, NNN = %x, KK = %x \n",
test_opcode.I,
test_opcode.X,
test_opcode.Y,
test_opcode.J,
test_opcode.NNN,
test_opcode.KK
);
输出是
I = d, X = 0, Y = 0, J = 0, NNN = 0, KK = 0
我正在编译这段代码Apple LLVM version 8.1.0 (clang-802.0.42)
使用以下 CMakeLists.txt:
cmake_minimum_required(VERSION 3.9)
project (Chip8)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set (CMAKE_CXX_STANDARD 11 REQUIRED)
find_package(Curses REQUIRED)
include_directories(${CURSES_INCLUDE_DIR}/src)
add_executable (Chip8 src/main.c src/Chip8State.c)
target_link_libraries(Chip8 ${CURSES_LIBRARIES})
为什么test_opcode.I == 0xD,为什么其余成员都是0x0?
我假设这是因为当我只需要一个 4 位数字时我正在使用 uint8_t,但我认为使用位域可以解决这个问题。
有没有办法可以修改我的 typedef 以具有上述所需的属性?
(我知道我可以使用掩码和位移来获得所需的值,我只是认为这种语法会更好)
提前致谢!
编辑:我将我的 CMakeList 改为拥有set(CMAKE_C_STANDARD_REQUIRED 11)
,因为我的意思是有一个 C 项目而不是 C++,但是我的代码仍然无法正常工作。