简体   繁体   English

如何将两个字节作为一个int(或类似的东西)存储在BYTE数组中?

[英]How to store two bytes in a BYTE array as an int (or something similar)?

I am writing a bittorrent client in C++ that receives a message from a tracker (server) containing several 6 byte strings. 我正在用C ++编写一个bittorrent客户端,该客户端从包含几个6字节字符串的跟踪器(服务器)接收消息。 The first 4 bytes represent the IP address of a peer and the next 2 bytes represent the port number that the peer is listening on. 前4个字节代表对等方的IP地址,后2个字节代表对等方正在侦听的端口号。

I have worked out how to convert the ip bytes into a human readable ip address but am struggling to convert the two bytes representing the port number into an int (or something similar) 我已经解决了如何将ip字节转换为人类可读的ip地址,但是正在努力将代表端口号的两个字节转换为int(或类似形式)

Here are my efforts so far: 到目前为止,这是我的努力:

BYTE portbinary[2];
unsigned short peerport;

//trackers[i]->peersBinary[j * 6 + 4] is the first byte
portbinary[0] = trackers[i]->peersBinary[j * 6 + 4];
//trackers[i]->peersBinary[j * 6 + 5] is the second byte
portbinary[1] = trackers[i]->peersBinary[j * 6 + 5];
peerport = *portbinary;

Upon examination peerport only seems to contain the integer representation of the first byte, how might I be able to fix this? 经检查,peerport似乎仅包含第一个字节的整数表示,我怎么能解决这个问题?

Thanks in advance :) 提前致谢 :)

我更喜欢使用按位运算而不是类型修剪,因为它根本不会引起字节序问题(端口号是大字节序号,当今许多系统都是小字节序)。

int peerport = (portbinary[0] << 8) | portbinary[1];

由于看起来数据已经对齐,因此您可以使用

peerport = ntohs(*(uint16_t *)(trackers[i]->peersBinary + j * 6 + 4));

Since portbinary is an array of BYTE , then *portbinary is equivalent to portbinary[0] . 由于portbinaryBYTE的数组,因此*portbinary等效于portbinary[0]

A portable way to to achieve your result could be: 一种实现结果的可移植方法可能是:

peerport = portbinary[0];
peerport = 256*peerport + portbinary[1];

This assumes portbinary was delivered in network byte order. 假定portbinary以网络字节顺序交付。

Solution with unions: 工会的解决方案:

union port_extractor
{
    BYTE raw_port[2];
    unsigned short port_assembled;
};

This will work if your computer endianess is the same as of representation you fetch from the network. 如果计算机的耐久性与从网络获取的表示形式相同,则此方法将起作用。 Sorry, I dont know how it comes by bittorrent protocol. 抱歉,我不知道bittorrent协议是怎么来的。

If the endianess is the opposite, then the solution you are bound to use is not as nice: 如果endianess相反,那么您必须使用的解决方案就不太好了:

unsigned short port_assembled = (unsigned short)raw_port[first_byte] | ((unsigned short)raw_port[second_byte] << 8);
// first_byte = 0, second_byte = 1 or vice versa 
// depending on source data endianess

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM