![](/img/trans.png)
[英]error: invalid conversion from 'short unsigned int*' to 'short unsigned int'| (in c++)
[英]short int to unsigned int conversion network byte order C++
我有一個兩字節的short int指針數組short int* hostdata
並希望將其轉換為網絡字節順序為unsigned int* net_data
的4字節unsigned int。 我可以這樣寫嗎?
for(int i = 0; i < numsamples; ++i)
net_data[i] = htonl((unsigned int)hostdata[i]);
還是我應該使用reinterpret_cast來做到這一點:
for(int i = 0; i < numsamples; ++i)
net_data[i] = htonl(reinterpret_cast<unsigned int *>(reinterpret_cast<short int*>hostdata[i]));
如果使用short integers
,那么在可以使用htons
時為什么要使用htonl
。
htonl代表長期聯網的主機
htons代表主機到網絡的短路
請記住,除了像stonhl
這樣的愚蠢組合之外,幾乎所有h,n,l,s組合都存在
不要使事情過於復雜,將它們添加到結構中,然后將其發送。
struct MsgHead
{
unsigned short utype;
unsigned short usize;
};
// 8 bytes, no padding will be added by the compiler
struct MyPacket
{
// Header (optional)
MsgHead head; // 4 bytes
unsigned short myData[2]; // 4 bytes
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.