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

发布于 2024-11-30 12:55:25 字数 338 浏览 3 评论 0原文

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

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

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

I have 8 bit samples with random values (called headers) and I have commands with hexadecimal values, see bellow:

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

How do you translate the 8 bit samples to 1 byte and join it with the above hex value ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱皱眉﹌ 2024-12-07 12:55:25

在这两种语言中,您都可以使用按位运算

因此,在 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);

In both languages, you can use bitwise operations.

So in C, if you have:

uint32_t command;
uint8_t  sample;

You can concatenate these into e.g. a 64-bit data type as follows:

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

If you instead want an array of output bytes (for serializing over RS-232 or whatever), then you can do something like:

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文