【问题标题】:Convert 2 bytes into an integer将 2 个字节转换为整数
【发布时间】:2013-06-08 22:00:44
【问题描述】:

我收到一个 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 字节 vs 4 字节:short vs int
  • 使用 uint16_t 进行转换

标签: c integer type-conversion byte


【解决方案1】:

我收到一个 2 字节的端口号(最低有效字节在前)

然后你可以这样做:

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

【讨论】:

  • @user1367988 请注意以防char 在该平台上签名。
  • 这个答案不正确,Joachim's 是正确的。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:
      char buf[2]; //Where the received bytes are
      int number;
      number = *((int*)&buf[0]);
      

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

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

      char buf[2]; //Where the received bytes are
      int number;  
      *((char*)&number) = buf[1];
      *((char*)&number+1) = buf[0];
      

      【讨论】:

        猜你喜欢
        • 2021-03-14
        • 1970-01-01
        • 2011-02-09
        • 2014-04-18
        • 1970-01-01
        • 2013-09-27
        • 1970-01-01
        • 2021-03-24
        相关资源
        最近更新 更多