在 C 中将字节转换为 Int/uint [英] Convert Bytes to Int / uint in C
问题描述
我有一个无符号字符数组[248];充满字节.像 2F AF FF 00 EB AB CD EF .....这个数组是我的字节流,我将来自 UART (RS232) 的数据作为缓冲区存储.
现在我想将字节转换回我的 uint16 和 int32.
在 C# 中,我使用 BitConverter 类来执行此操作.例如:
byte[] Array = { 0A, AB, CD, 25 };int myint1 = BitConverter.ToInt32(bytes, 0);int myint2 = BitConverter.ToInt32(bytes, 4);int myint3 = BitConverter.ToInt32(bytes, 8);int myint4 = BitConverter.ToInt32(bytes, 12);//...在此处输入代码Console.WriteLine("int: {0}", myint1);//输出数据...
C 中有类似的函数吗?(没有 .net ,我使用 KEIL 编译器,因为代码在微控制器上运行)
问候山姆
是的.假设您的字节在:
uint8_t bytes[N] = {/* 随便 */};
我们知道,一个 16 位整数只是两个 8 位整数连接在一起,即一个是 256 的倍数或移位 8:
uint16_t 十六[N/2];对于 (i = 0; i
同样适用于 32 位:
uint32_t三十二[N/4];对于 (i = 0; i
<小时>
如果字节是大端读取的,当然你要颠倒顺序:
bytes[i+1] |(uint16_t)bytes[i] <<8
和
bytes[i+3] |(uint32_t)bytes[i+2] <<8|(uint32_t)bytes[i+1] <<16 |(uint32_t)bytes[i] <<24
请注意,存储整数的字节序与运行架构的字节序之间存在差异.这个答案中提到的字节序是存储的整数,即 bytes
的内容.由于移位时会考虑字节序,因此解决方案与正在运行的架构的字节序无关.>
I have a unsigned char array[248]; filled with bytes. Like 2F AF FF 00 EB AB CD EF ..... This Array is my Byte Stream which I store my Data from the UART (RS232) as a Buffer.
Now I want to convert the bytes back to my uint16's and int32's.
In C# I used the BitConverter Class to do this. e.g:
byte[] Array = { 0A, AB, CD, 25 };
int myint1 = BitConverter.ToInt32(bytes, 0);
int myint2 = BitConverter.ToInt32(bytes, 4);
int myint3 = BitConverter.ToInt32(bytes, 8);
int myint4 = BitConverter.ToInt32(bytes, 12);
//...
enter code here
Console.WriteLine("int: {0}", myint1); //output Data...
Is there a similiar Function in C ? (no .net , I use the KEIL compiler because code is running on a microcontroller)
With Regards Sam
Yes there is. Assume your bytes are in:
uint8_t bytes[N] = { /* whatever */ };
We know that, a 16 bit integer is just two 8 bit integers concatenated, i.e. one has a multiple of 256 or alternatively is shifted by 8:
uint16_t sixteen[N/2];
for (i = 0; i < N; i += 2)
sixteen[i/2] = bytes[i] | (uint16_t)bytes[i+1] << 8;
// assuming you have read your bytes little-endian
Similarly for 32 bits:
uint32_t thirty_two[N/4];
for (i = 0; i < N; i += 4)
thirty_two[i/4] = bytes[i] | (uint32_t)bytes[i+1] << 8
| (uint32_t)bytes[i+2] << 16 | (uint32_t)bytes[i+3] << 24;
// same assumption
If the bytes are read big-endian, of course you reverse the order:
bytes[i+1] | (uint16_t)bytes[i] << 8
and
bytes[i+3] | (uint32_t)bytes[i+2] << 8
| (uint32_t)bytes[i+1] << 16 | (uint32_t)bytes[i] << 24
Note that there's a difference between the endian-ness in the stored integer and the endian-ness of the running architecture. The endian-ness referred to in this answer is of the stored integer, i.e., the contents of bytes
. The solutions are independent of the endian-ness of the running architecture since endian-ness is taken care of when shifting.
这篇关于在 C 中将字节转换为 Int/uint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!