- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有一堆测试 vector ,以十六进制字符串的形式呈现:
MSG: 6BC1BEE22E409F96E93D7E117393172A
MAC: 070A16B46B4D4144F79BDD9DD04A287C
MSG: 6BC1BEE22E409F96E93D7E117393172AAE2D8A57
MAC: 7D85449EA6EA19C823A7BF78837DFADE
等等。我需要以某种方式将它们放入 C++ 程序中,而不需要太多的编辑。有多种选择:
0x6B,0xC1,0xBE,...
形式但我最终使用的是:
因为好玩。我定义了一个助手类 HexByteArray
和一个用户定义的文字运算符 HexByteArray operator "" _$ (const char* s)
解析 "0xXX...XX"
形式的字符串, 其中 XX...XX
是偶数个十六进制数字。 HexByteArray
包括到 const uint8_t*
的转换运算符和 std::vector<uint8_t>
.所以现在我可以写例如
struct {
std::vector<uint8_t> MSG ;
uint8_t* MAC ;
} Test1 = {
0x6BC1BEE22E409F96E93D7E117393172A_$,
0x070A16B46B4D4144F79BDD9DD04A287C_$
} ;
效果很好。但现在这是我的问题:我也可以对数组执行此操作吗?例如:
uint8_t MAC[16] = 0x070A16B46B4D4144F79BDD9DD04A287C_$ ;
甚至
uint8_t MAC[] = 0x070A16B46B4D4144F79BDD9DD04A287C_$ ;
我不知道如何进行这项工作。要初始化一个数组,我似乎需要一个 std::initializer_list
.但据我所知,只有编译器可以实例化这样的东西。有什么想法吗?
这是我的代码:
HexByteArray.h
#include <cstdint>
#include <vector>
class HexByteArray
{
public:
HexByteArray (const char* s) ;
~HexByteArray() { delete[] a ; }
operator const uint8_t*() && { const uint8_t* t = a ; a = 0 ; return t ; }
operator std::vector<uint8_t>() &&
{
std::vector<uint8_t> v ( a, a + len ) ;
a = 0 ;
return v ;
}
class ErrorInvalidPrefix { } ;
class ErrorHexDigit { } ;
class ErrorOddLength { } ;
private:
const uint8_t* a = 0 ;
size_t len ;
} ;
inline HexByteArray operator "" _$ (const char* s)
{
return HexByteArray (s) ;
}
HexByteArray.cpp
#include "HexByteArray.h"
#include <cctype>
#include <cstring>
HexByteArray::HexByteArray (const char* s)
{
if (s[0] != '0' || toupper (s[1]) != 'X') throw ErrorInvalidPrefix() ;
s += 2 ;
// Special case: 0x0_$ is an empty array (because 0x_$ is invalid C++ syntax)
if (!strcmp (s, "0"))
{
a = nullptr ; len = 0 ;
}
else
{
for (len = 0 ; s[len] ; len++) if (!isxdigit (s[len])) throw ErrorHexDigit() ;
if (len & 1) throw ErrorOddLength() ;
len /= 2 ;
uint8_t* t = new uint8_t[len] ;
for (size_t i = 0 ; i < len ; i++, s += 2)
sscanf (s, "%2hhx", &t[i]) ;
a = t ;
}
}
最佳答案
使用 numeric literal operator template , 签名:
template <char...>
result_type operator "" _x();
另外,由于数据在编译时是已知的,我们不妨将所有内容都设为 constexpr
。请注意,我们使用 std::array
而不是 C 样式的数组:
#include <cstdint>
#include <array>
#include <vector>
// Constexpr hex parsing algorithm follows:
struct InvalidHexDigit {};
struct InvalidPrefix {};
struct OddLength {};
constexpr std::uint8_t hex_value(char c)
{
if ('0' <= c && c <= '9') return c - '0';
// This assumes ASCII:
if ('A' <= c && c <= 'F') return c - 'A' + 10;
if ('a' <= c && c <= 'f') return c - 'a' + 10;
// In constexpr-land, this is a compile-time error if execution reaches it:
// The weird `if (c == c)` is to work around gcc 8.2 erroring out here even though
// execution doesn't reach it.
if (c == c) throw InvalidHexDigit{};
}
constexpr std::uint8_t parse_single(char a, char b)
{
return (hex_value(a) << 4) | hex_value(b);
}
template <typename Iter, typename Out>
constexpr auto parse_hex(Iter begin, Iter end, Out out)
{
if (end - begin <= 2) throw InvalidPrefix{};
if (begin[0] != '0' || begin[1] != 'x') throw InvalidPrefix{};
if ((end - begin) % 2 != 0) throw OddLength{};
begin += 2;
while (begin != end)
{
*out = parse_single(*begin, *(begin + 1));
begin += 2;
++out;
}
return out;
}
// Make this a template to defer evaluation until later
template <char... cs>
struct HexByteArray {
static constexpr auto to_array()
{
constexpr std::array<char, sizeof...(cs)> data{cs...};
std::array<std::uint8_t, (sizeof...(cs) / 2 - 1)> result{};
parse_hex(data.begin(), data.end(), result.begin());
return result;
}
constexpr operator std::array<std::uint8_t, (sizeof...(cs) / 2)>() const
{
return to_array();
}
operator std::vector<std::uint8_t>() const
{
constexpr auto tmp = to_array();
return std::vector<std::uint8_t>{tmp.begin(), tmp.end()};
}
};
template <char... cs>
constexpr auto operator"" _$()
{
static_assert(sizeof...(cs) % 2 == 0, "Must be an even number of chars");
return HexByteArray<cs...>{};
}
示例用法:
auto data_array = 0x6BC1BEE22E409F96E93D7E117393172A_$ .to_array();
std::vector<std::uint8_t> data_vector = 0x6BC1BEE22E409F96E93D7E117393172A_$;
附带说明,identifier 中的 $
实际上是一个 gcc 扩展,所以它是非标准的 C++。考虑使用 _$
以外的 UDL。
关于c++ - 使用 C++ 用户定义的文字来初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913800/
由于 typescript 现在支持条件类型,我决定进行一些元编程,为 VSCODE intellisense 添加更多 flavor 。但是,虽然使用 A extends B 可以轻松分离其他类型,
我有一个 php var,它在回显时将 JS 函数写入页面的源代码。该函数循环遍历 CSV,因此其中包含以下行: $str="var lines = data.split('\n');"; 目前,当回
我有以下代码: name= "a"; value="b" $.post("ajax.php", {name:value}).... 然而 ajax.php 将收到 name=b 而不是 a=b。 我如
以下情况: var myVehicle = { brand: 'Tesla' }; var isMoving = Symbol(); var currentStatus = Symbol(); myV
我正在为 Python 翻译器编写 JavaScript,“\8”和“\9”给我带来了很多问题。根据文档,像“\8”或“\9”这样的东西是非法的,因为它们不是有效的八进制转义符。 Esprima pa
我有一个简单的 LinearLayout。当我将 android:background 添加到 LinearLayout 时,TextView 不再可见。 我不明白什么?
在尝试获得某种效果时遇到困难: 我有一张图片。我想将鼠标悬停在它上面。它应该变黑并弹出一些文本。 例子^ 执行此操作最简单/最简单的设置是什么?最好只有 HTML 和 CSS 注意:该元素需要在 CS
考虑以下代码: #include void f(const char * str) { str = "java"; } void main (int argc, char * argv[])
我想在 MySQL 中插入一条具有非 ASCII Unicode 字符的记录,但我在一个不允许我轻松键入非 ASCII 字符的终端上。如何在 MySQL 的 SQL 语法中转义 Unicode 文字?
Perl脚本batchReplace.pl可以用来批量替换文件中的文字/代码。可在指定目录中查找指定类型的文件,并递归检查子目录;在输出文件时复制输入文件的目录结构。 [附件]Win32应用程序b
我知道从 flutter 应用程序共享的官方包。 https://pub.dartlang.org/packages/share 共享文本和 url 很容易,但我想共享来自服务器的图像意味着它是 UR
在 Qt 文档中,它说 qreal是一个 Typedef for double unless Qt is configured with the -qreal float option. 这基本上意味
我想让 idris 证明 testMult : mult 3 3 = 9有人居住。 不幸的是,这是键入为 mult (fromInteger 3) (fromInteger 3) = fromInte
如您所知,Apple 为 NSNumber、NSDictionary、NSArray 等类提供了 @literals,因此我们可以通过这种方式创建对象,例如 NSArray *array = @[ob
有没有办法在类型上定义公共(public)文字(C# 中的公共(public) const)?显然 let 类型中的绑定(bind)必须是私有(private)的,并且 Literal 属性不能应用于
为什么下面的语法不能识别 bool 值? 我已经将其与 Java 和 GraphQL 的语法进行了比较,但不明白为什么它不起作用。 给定以下语法,解析如下: foo = null // foo = v
当我需要一个文字来测试一个带有序列的函数时,我注意到我自己的习惯比列表更频繁地使用向量。 IE。 : (map inc [1 2 3]) 但不是: (map inc (list 1 2 3)) 虽然它
是否可以在sqlite中制作类似的东西? FOREIGN KEY(TypeCode, 'ARawValue', IdServeur) REFERENCES OTHERTABLE(TypeCode, T
在我这学期的系统软件类(class)中,我们正在学习汇编程序和其他系统软件。在阅读整个类(class)时,我遇到了LITERALS主题。 对文字和立即操作数进行了比较,发现它们之间的唯一区别是文字不被
我正在使用命令行语法编写一个 gstreamer 管道来发送视频流,并想用它发送数据。我认为可行的一种解决方案是将数据作为字幕文件发送。 我可以使用以下管道通过 rtp 多路复用视频和字幕文件: gs
我是一名优秀的程序员,十分优秀!