将2个字节转换为整数

25

我收到的端口号是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));

然而,有些问题,因为我没有获得正确的端口号。有任何想法吗?


你的字节序相同吗? - im so confused
1
也就是2个字节和4个字节:short和int。 - im so confused
1
使用uint16_t进行类型转换。 - im so confused
5个回答

37

我会收到一个由2个字节构成的端口号(从低位字节开始)

然后您可以进行以下操作:

  int number = buf[0] | buf[1] << 8;

5
@user1367988,在这个平台上要注意char是否被视为有符号数。 - Joachim Isaksson
@AnttiHaapala-- СлаваУкраїні 这为什么是不正确的?它看起来等同于Joachim的。 - kwc
这个答案是错误的,如果字节中有符号位设置,将在x86上严重崩溃,除非您对缓冲区使用unsigned char。@kwc joachim说:“如果你把它变成unsigned char”。我删除了评论,因为虽然Joachim的答案更正确,但仍然不是100%可移植的-对于16位整数,它会引发未定义的行为。但是,如果缓冲区的类型不改变,则此答案在x86和有符号字符上非常破碎,因为两者都转换为有符号的。 - Antti Haapala -- Слава Україні

15

如果将buf改为unsigned char buf[2];,您可以将其简化为:

number = (buf[1] << 8) + buf[0];

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;
}

0

最不显著字节: int number = (uint8_t)buf[0] | (uint8_t)buf[1] << 8;

最显著字节: int number = (uint8_t)buf[1] << 8 | (uint8_t)buf[0];


-2
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];

这个答案不正确。它违反了严格的别名规则,也可能违反对齐要求。 - Antti Haapala -- Слава Україні

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接