![](/img/trans.png)
[英]How to convert IP address (both ipv4 and ipv6) to binary in C++?
[英]How to convert a binary IPv6 address into hexadecimal
我收到的是128位二進制地址,我需要將其轉換為十六進制格式。 這是我要做的:
我需要將其划分為8個16位的塊,因此我將有8個變量每個16位。
0010000111011010 0000000011010011 0000000000000000 0010111100111011 0000001010101010 0000000011111111 0000000000000000 0000000000000000
現在,我需要將這16位進一步分為4位,即四位
0010 0001 1101 1010
0000 0000 1101 0011
0000 0000 0000 0000
所以,現在我將為每個變量獲取四個子變量
然后,我需要將每個子變量轉換為十六進制
0010 0001 1101 1010
2 1 DA
合並所有子變量,以十六進制形式形成一個IPv6地址:
21DA:00D3:0000:2F3B:02AA:00FF:0000:0000
誰能告訴我如何用C ++做到這一點?
要獲得16位值的四個最高位,請將其右移12位。 這將導致高位為零,因此不需要屏蔽。 對於其他人,您(可選)向右移動並使用按位和運算符&
屏蔽掉最低的四個位。
若要將通過上述步驟獲得的值轉換為字符形式的十六進制數字,則對於小於10的值,請添加'0'
(如果您使用的是ASCII編碼的計算機),對於大於或等於10的值,請減去十並添加例如'A'
。
當然,有更簡單的方法,例如使用sprintf
直接轉換數字。 只需將16位值轉換成無符號的short,然后執行例如
printf("%04hx\n", value_as_unsigned_short);
假設您的二進制數為0001001010101011
。 這是十六進制表示形式12ab
。
如果二進制數在一個整數變量中,可以說一個命名value
,我們可以將十六進制表示形式表示為一個字符串,如下所示:
// First get each digit, one by one
digit0 = value & 0x0f; // Mask out everything but the lowest four bits
digit1 = (value >> 4) 0x0f;
digit2 = (value >> 8) 0x0f;
digit3 = value >> 12;
// Now make a string out of those four digits
char str[5]; // Four digits plus the string terminator
// If a digit is less than 10, then add '0' to get an ASCII character
// Else decrease by ten (to get a number between 0 and 5) and add 'A'
str[0] = digit3 < 10 ? digit3 + '0' : (digit3 - 10) + 'A';
str[1] = digit2 < 10 ? digit2 + '0' : (digit2 - 10) + 'A';
str[2] = digit1 < 10 ? digit1 + '0' : (digit1 - 10) + 'A';
str[3] = digit0 < 10 ? digit0 + '0' : (digit0 - 10) + 'A';
str[4] = '\0'; // Terminate string
printf("value is in hex %s\n", str);
上面的代碼將打印
value is in hex 12AB
但這是很多代碼,盡管可以將其重用於所有數字。 如果您已經在整數變量value
包含16位數字,則編寫起來會容易得多
printf("value is in hex %04hX\n", value);
上面兩個代碼片段的結果將是相同的。
關於您的編輯:
std::ostringstream oss;
for (size_t i = 0; i < 8; ++i, aBinaryIPAddress += 2)
{
// Take the first byte, and shift it left 8 bits, making it
// the high byte of a 16-bit number. Then or (or add) the next
// byte at the low 8 bits in the 16-bit number.
// The casting is needed because we're working with 16-bit numbers
// and not bytes.
uint16_t value = static_cast<uint16_t>(*aBinaryIPAddress << 8) |
static_cast<uint16_t>(*(aBinaryIPAddress + 1));
oss << std::setfill('0') << std::setw(4) << std::hex << value;
if (i < 7)
oss << ':';
}
std::cout << "Address is " << oss.str() << '\n';
您可以使用sprintf和格式說明符X將整數值打印為十六進制。 無需將每個塊划分為超過4個字節。 因此,如果您有:
string a = "00100001110110100000000011010011";
unsigned value = 0;
for (int i = 0;i < a.size();++i) {
value = value * 2 + a[i] - '0';
}
printf("%04X\n", value);
將解決您的大部分問題。 我在上面使用了printf來演示stdout上的輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.