将2个字节转换为整数

时间:2013-06-12 17:16:11

标签: 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));

然而,有一些错误,因为我没有得到正确的端口号。有任何想法吗?

4 个答案:

答案 0 :(得分:23)

  

我收到的端口号为2个字节(最低有效字节优先)

然后你可以这样做:

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

答案 1 :(得分:5)

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

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

答案 2 :(得分:4)

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

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

答案 3 :(得分:0)

 var dataJson = {labels: ['07:00', '10:00', '12:00', '14:00'],
 series: [333, 444, 322, 222]} 

new Chartist.Line('.ct-chart', {
labels: dataJson.labels,
series: [dataJson.series]
}, {
   fullWidth: true,
   chartPadding: {
   right: 40
  }
});

char buf[2]; //Where the received bytes are int number; number = *((int*)&buf[0]); 接受buf中第一个字节的地址。
&buf[0]将其转换为整数指针。
最左边的(int*)从该内存地址读取整数。

如果您需要交换字节序:

*