无符号整数半字节被视为二进制压缩为无符号整数

Unsigned integer nibbles treated as binary compressed to unsigned integer

我想出了以下使用无符号整数表示二进制的方法。例如:0x1111 存储为 0xf(15).
我知道已经有解决方案,如 BOOST_BINARYC++14 二进制文字和宏技巧来表示二进制数。
我只是想让它与模板一起工作(受阶乘示例的启发)。
以下解决方案足以完成我手头的任务。

任何关于如何使用模板而不是宏将其扩展到 uint64_t 以上(也没有 C++14 但只有 C++11)或如何改进 this/loop 洞?我只是好奇。
谢谢

template <>
struct Uint64Nibbles2Binary<0x0>
{
  enum {value = 0x0};
};

template <uint64_t num>
struct Uint64Nibbles2Binary
{
  enum 
  {
    value = (Uint64Nibbles2Binary<(num >> 4)>::value << 0x1) | (num & 0x1);
  };
};

在 C++14 中,只需使用 0b1111。并做了。他们有内置的二进制文字支持。

在 C++11 中,您需要使用 operator"".

constexpr int64_t make_binary() { return 0; }

template<class...Rest>
constexpr int64_t make_binary( char C, Rest...rest ) {
  return ((C=='1') << sizeof...(Rest)) + make_binary(rest...);
}

template <char...Cs>
constexpr int64_t operator"" _binary() {
  static_assert(sizeof...(Cs) <= 64, "Binary value has too many bits");
  return make_binary(Cs...);
}

然后:

111011110101101_binary

是编译时计算的二进制字面量。

live example

二进制输出的大小受 64 位 int 的限制。输入自然限制为 64 位。不使用前缀。可以在编译时进行错误检查以消除非 0 和非 1 值。