java - 如何在java或c中从8位样本中生成1个字节?

标签 java c protocols

我有带有随机值(称为 header )的 8 位样本,并且有带有十六进制值的命令,请参见以下内容:

[8 bit][command]
 \      |
  \     \------------------ [01 30 00 00 = hex start the machine]
   \
   +-------------------+
   | 00001111 = hi     |
   | 00000000 = hello  |
   | 00000101 = wassup |
   +-------------------+

如何将 8 位样本转换为 1 字节并将其与上述十六进制值连接?

最佳答案

在两种语言中,您都可以使用 bitwise operations .

所以在 C 语言中,如果你有:

uint32_t command;
uint8_t  sample;

您可以将它们连接成例如64 位数据类型如下:

uint64_t output = (uint64_t)command << 32
                | (uint64_t)sample;

如果您想要一个输出字节数组(用于通过 RS-232 或其他方式进行序列化),那么您可以执行以下操作:

uint8_t output[5];
output[0] = sample;
output[1] = (uint8_t)(command >>  0);
output[2] = (uint8_t)(command >>  8);
output[3] = (uint8_t)(command >> 16);
output[4] = (uint8_t)(command >> 32);

关于java - 如何在java或c中从8位样本中生成1个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7119880/

相关文章:

java - 字符串数组不匹配

java - Maven tomcat6 插件将资源/属性文件复制到自定义路径

objective-c - 在 Objective c 中如何定义自定义 boolean 类型?

java - Antlr4如何检测无法识别的 token 和给定的句子无效

java - 在 jsf 2 中处理用户 session

c - 适用于应用程序的可移植 Linux 环境

android - 在 eclipse android 应用程序中使用 native 代码

swift - 必须指定 Swift 协议(protocol)中的初始化程序。为什么呢?

ios - Swift - 枚举的子类(或类似的东西)

networking - Linux 网络堆栈 : adding protocols with an LKM and dev_add_pack