C语言 将 2 个字节转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17071458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert 2 bytes into an integer
提问by user1367988
I receive a port number as 2 bytes (least significant byte first) and I want to convert it into an integer so that I can work with it. I've made this:
我收到一个 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));
However, there's something wrong because I don't get the correct port number. Any ideas?
但是,有一些问题,因为我没有得到正确的端口号。有任何想法吗?
回答by nos
I receive a port number as 2 bytes (least significant byte first)
我收到一个 2 个字节的端口号(最低有效字节在前)
You can then do this:
然后你可以这样做:
int number = buf[0] | buf[1] << 8;
回答by Joachim Isaksson
If you make buf into an unsigned char buf[2], you could just simplify it to;
如果你把 buf 变成 an unsigned char buf[2],你可以把它简化为;
number = (buf[1]<<8)+buf[0];
回答by Pitpat
I appreciate this has already been answered reasonably. However, another technique is to define a macro in your code eg:
我很感激这已经得到了合理的回答。但是,另一种技术是在您的代码中定义一个宏,例如:
// 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;
}
回答by mcgurk
char buf[2]; //Where the received bytes are
int number;
number = *((int*)&buf[0]);
&buf[0]takes address of first byte in buf.(int*)converts it to integer pointer.
Leftmost *reads integer from that memory address.
&buf[0]获取 buf 中第一个字节的地址。(int*)将其转换为整数指针。
最左边*从该内存地址读取整数。
If you need to swap endianness:
如果您需要交换字节顺序:
char buf[2]; //Where the received bytes are
int number;
*((char*)&number) = buf[1];
*((char*)&number+1) = buf[0];

