C 将2个字节转换为整数
我收到一个2字节的端口号(首先是最低有效字节),我想把它转换成一个整数,这样我就可以使用它了。我做了这个:C 将2个字节转换为整数,c,integer,type-conversion,byte,C,Integer,Type Conversion,Byte,我收到一个2字节的端口号(首先是最低有效字节),我想把它转换成一个整数,这样我就可以使用它了。我做了这个: char buf[2]; //Where the received bytes are char port[2]; port[0]=buf[1]; port[1]=buf[0]; int number=0; number = (*((int *)port)); 但是,出现了一些问题,因为我没有得到正确的端口号。有什么想法吗 我以2字节的形式接收端口号(最低有效字节优先) 然后
char buf[2]; //Where the received bytes are
char port[2];
port[0]=buf[1];
port[1]=buf[0];
int number=0;
number = (*((int *)port));
但是,出现了一些问题,因为我没有得到正确的端口号。有什么想法吗
我以2字节的形式接收端口号(最低有效字节优先)
然后,您可以执行以下操作:
int number = buf[0] | buf[1] << 8;
int number=buf[0]| buf[1]如果将buf转换为无符号字符buf[2]
,则可以将其简化为
number = (buf[1]<<8)+buf[0];
number=(buf[1]我知道这已经得到了合理的回答。但是,另一种技术是在代码中定义宏,例如:
// bytes_to_int_example.cpp
// Output: port = 514
// I am assuming that the bytes the bytes need to be treated as 0-255 and combined MSB -> LSB
// This creates a macro in your code that does the conversion and can be tweaked as necessary
#define bytes_to_u16(MSB,LSB) (((unsigned int) ((unsigned char) MSB)) & 255)<<8 | (((unsigned char) LSB)&255)
// Note: #define statements do not typically have semi-colons
#include <stdio.h>
int main()
{
char buf[2];
// Fill buf with example numbers
buf[0]=2; // (Least significant byte)
buf[1]=2; // (Most significant byte)
// If endian is other way around swap bytes!
unsigned int port=bytes_to_u16(buf[1],buf[0]);
printf("port = %u \n",port);
return 0;
}
//bytes\u to\u int\u example.cpp
//输出:端口=514
//我假设需要将字节处理为0-255并组合MSB->LSB
//这将在代码中创建一个宏来进行转换,并可根据需要进行调整
#定义字节_到_16(MSB,LSB)((无符号int)((无符号字符)MSB))&255)
&buf[0]
获取buf中第一个字节的地址。
(int*)
将其转换为整数指针。
最左边的*
从该内存地址读取整数
如果需要交换端点,请执行以下操作:
char buf[2]; //Where the received bytes are
int number;
*((char*)&number) = buf[1];
*((char*)&number+1) = buf[0];
你的结尾是一样的吗?同样是2字节对4字节:短对直觉cast@user1367988小心,以防char
在该平台上签名。这个答案是错误的,是正确的。
char buf[2]; //Where the received bytes are
int number;
*((char*)&number) = buf[1];
*((char*)&number+1) = buf[0];