Skip to content

Instantly share code, notes, and snippets.

@likev
Created August 6, 2017 08:17
Show Gist options
  • Save likev/6ebd043f13a895b095d4541838d0d10b to your computer and use it in GitHub Desktop.
Save likev/6ebd043f13a895b095d4541838d0d10b to your computer and use it in GitHub Desktop.
convert between Big-endian(TCP/IP network) byte order and Little-endian(host) byte order
namespace nh {
auto htons = [](unsigned short h)
{
return (unsigned short)
( h << 8 & 0xFF00U |
h >> 8 & 0x00FFU );
};
auto htonl = [](unsigned int h)
{
return (unsigned int)
( h << 24 & 0xFF000000U |
h << 8 & 0x00FF0000U |
h >> 8 & 0x0000FF00U |
h >> 24 & 0x000000FFU );
};
auto ntohs = htons;
auto ntohl = htonl;
}
/*------ test code -----------
// vs2017 on win7
#include <iostream>
#include <Winsock2.h>
#pragma comment(lib, "ws2_32.lib")
void byte_order()
{
unsigned short a = 0x1234U;
std::cout << std::showbase << std::hex;
std::cout << "a = " << a << std::endl;
std::cout << "ntohs(a) = " << ntohs(a) << std::endl;
std::cout << "htons(a) = " << htons(a) << std::endl;
std::cout << "nh::htons(a) = " << nh::htons(a) << std::endl;
std::cout << "nh::ntohs(a) = " << nh::ntohs(a) << std::endl;
unsigned b = 0x12345678u;
std::cout << "b = " << b << std::endl;
std::cout << "ntohl(b) = " << ntohl(b) << std::endl;
std::cout << "htonl(b) = " << htonl(b) << std::endl;
std::cout << "nh::htonl(b) = " << nh::htonl(b) << std::endl;
std::cout << "nh::ntohl(b) = " << nh::ntohl(b) << std::endl;
}
int main()
{
byte_order();
}
------------------------------*/
/*------ test code output-----
a = 0x1234
ntohs(a) = 0x3412
htons(a) = 0x3412
nh::htons(a) = 0x3412
nh::ntohs(a) = 0x3412
b = 0x12345678
ntohl(b) = 0x78563412
htonl(b) = 0x78563412
nh::htonl(b) = 0x78563412
nh::ntohl(b) = 0x78563412
--------------------------------*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment