[英]How to make a word from Byte []?
I am new to programming world, I want to convert two bytes into a word. 我是编程世界的新手,我想将两个字节转换成一个单词。
So basically, I have a Byte array where index 0 is Buffer[0]=08
and index 1 is Buffer[1]=06
I want to create a word from these two bytes 所以基本上,我有一个字节数组,其中索引0是Buffer[0]=08
而索引1是Buffer[1]=06
我想从这两个字节创建一个字
where word ETHType to be 0x0806
其中字ETHType to be 0x0806
You would use bitwise operators and bit shifting. 您将使用按位运算符和位移位。
uint16_t result = ((uint16_t)Buffer[0] << 8) | Buffer[1];
This does the following: 这样做如下:
Buffer[0]
is shifted 8 bits to the left. Buffer[0]
的值向左移8位。 That gives you 0x0800 这给你0x0800 Buffer[1]
. 在先前值和Buffer[1]
的值之间执行按位OR。 This sets the low order 8 bits to Buffer[1]
, giving you 0x0806 这将低位8位设置为Buffer[1]
,给出0x0806 word ETHType = 0;
ETHType = (Buffer[0] << 8) | Buffer[1];
edit: You should probably add a mask to each operation to make sure there is no bit overlap, and you can do it safely in one line. 编辑:你应该为每个操作添加一个掩码,以确保没有位重叠,你可以安全地在一行中完成。
word ETHType = (unsigned short)(((unsigned char)(Buffer[0] & 0xFF) << 8) | (unsigned char)(Buffer[1] & 0xFF)) & 0xFFFF;
Here's a macro I use for this very thing: 这是我用于此事的一个宏:
#include <stdint.h>
#define MAKE16(a8, b8) ((uint16_t)(((uint8_t)(((uint32_t)(a8)) & 0xff)) | ((uint16_t)((uint8_t)(((uint32_t)(b8)) & 0xff))) << 8))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.