22

我收到一个 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));

但是,出现了问题,因为我没有得到正确的端口号。有任何想法吗?

4

4 回答 4

35

我收到一个 2 字节的端口号(首先是最低有效字节)

然后你可以这样做:

  int number = buf[0] | buf[1] << 8;
于 2013-06-12T17:20:13.357 回答
14

如果你做成buf一个unsigned char buf[2];,你可以将它简化为:

number = (buf[1] << 8) + buf[0];
于 2013-06-12T17:20:32.460 回答
7

我很感激这已经得到了合理的回答。但是,另一种技术是在代码中定义宏,例如:

// 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;
}
于 2016-07-17T03:14:28.413 回答
0
char buf[2]; //Where the received bytes are
int number;
number = *((int*)&buf[0]);

&buf[0]获取 buf 中第一个字节的地址。
(int*)将其转换为整数指针。
最左边*从该内存地址读取整数。

如果您需要交换字节顺序:

char buf[2]; //Where the received bytes are
int number;  
*((char*)&number) = buf[1];
*((char*)&number+1) = buf[0];
于 2020-02-03T16:02:22.077 回答