将枚举类型转换为C++
编写返回8位六角值数组的函数的最佳和最短方法是基于枚举参数分配的。
我需要硬代码命令,该命令将通过蓝牙发送,并且仍然可以轻松地使用代码访问它们。因此,我有一个以人类可读方式列出的所有可能命令的枚举。
enum eventType {
MODIFY_A,
MODIFY_B,
MODIFY_C,
MODIFY_D
}
我尝试调整的通信协议使用具有预定义十六进制值的自定义数据包。因此,例如,发送0x00、0x01、0x02、0x03
可以更改接收设备的LED颜色。
用于BLE通信的库接受所述hexes或其他单词的数组,只是一个普通的c字符串。
声明之后,简单地在switch()中简单地定义一个数组,这是最容易的,就像这样:
uint8_t* getCommandOf(eventType event) {
uint8_t command[4];
switch(event) {
case eventType::MODIFY_A:
command = {0x01, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_B:
command = {0x02, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_C:
command = {0x03, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_D:
command = {0x04, 0x00, 0x00, 0x00}; break;
}
return command;
}
然后我可以简单地调用: sendoverble(getCommandof(eventType :: modify_a));
不幸的是,我们不能在C ++中这样做。 我愿意接受建议。您将如何解决?尽管我有一些解决方案,但我不喜欢他们中的任何一个。
也许在2D数组中定义它们?还是自定义容器类?
What would be the most optimal and shortest way to write a function returning an array of 8-bit hex values, which are assigned based on an enumerated parameter.
I need to hard code commands, which will be sent over bluetooth and still have an easy access to them in code. So I have an enum with all possible commands listed in a human-readable way.
enum eventType {
MODIFY_A,
MODIFY_B,
MODIFY_C,
MODIFY_D
}
The communication protocol I try to adapt uses custom packets with predefined hex values. So for example, sending 0x00, 0x01, 0x02, 0x03
could change led colour of a receiving device.
The library used for ble communication accepts arrays of said hexes, or other words, just a plain C string.
It would be easiest to simply define an array in a switch() after declaring it, just like this:
uint8_t* getCommandOf(eventType event) {
uint8_t command[4];
switch(event) {
case eventType::MODIFY_A:
command = {0x01, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_B:
command = {0x02, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_C:
command = {0x03, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_D:
command = {0x04, 0x00, 0x00, 0x00}; break;
}
return command;
}
Then I could simply call:sendOverBLE(getCommandOf(eventType::MODIFY_A));
Unfortunately, we can't do that in C++.
I'm open to suggestions. How would you solve it? I though of a few solutions, butI don't like any of them.
Maybe define them in a 2d array? Or a custom container class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用并返回
std :: array
。 将您的功能更改为如果您需要将此数组传递到采用
uint8_t*
的函数,则可以 >成员可以得到这样的指针I would suggest using and returning a
std::array
. That would change your function toIf you need to pass this array to a function that takes a
uint8_t*
, then you can usearray
'sdata
member to get such a pointer like如果您完全控制您的
enum
,您可以将其定义如下:那么您的函数可以是:
If you're in complete control over your
enum
you could define it as follows:Then your function could be: