C++实现IPv4地址类:Bitset初始化与IP解析完善需求
Hey there! Let's get that bitset<8> bits[4] member set up correctly using the parsed octets from your IPv4 input.
Quick Background
Your current code already does a great job parsing the user's IP into the arr[4] array of unsigned char octets. Since each octet is an 8-bit value, initializing the bitset<8> array is straightforward—std::bitset has a constructor that takes an integer type, which we can use directly with each element of arr.
Updated Constructor Code
Here's how to modify your constructor to initialize the bitset array properly:
#include <iostream> #include <bitset> #include <cstring> class Address { private : unsigned char arr[4] = {0}; std::bitset<8> bits[4]; public : Address(){ char ip[50]; std::cout << "Enter your IP ADDRESS: "; std::cin >> ip; int k = 0; unsigned char current_octet = 0; for(int i = 0; ip[i] != '\0'; ++i){ if(ip[i] != '.'){ // Convert character digit to integer value current_octet = current_octet * 10 + (ip[i] - '0'); } else { // Store the parsed octet and initialize its bitset arr[k] = current_octet; bits[k] = std::bitset<8>(current_octet); current_octet = 0; ++k; } } // Handle the final octet (after the last dot) arr[k] = current_octet; bits[k] = std::bitset<8>(current_octet); } // Optional: Method to display the bits for testing void printBitRepresentation() const { for(int i = 0; i < 4; ++i){ std::cout << bits[i]; if(i != 3) std::cout << "."; } std::cout << "\n"; } };
Key Notes
- Initialize as you parse: By setting
bits[k]right after we finish parsing an octet (when we hit a '.'), we ensure we don't skip any values. We also handle the final octet outside the loop since there's no trailing dot. - Readable conversions: Using
ip[i] - '0'instead ofip[i] - 48makes the code easier to read—it clearly shows we're converting a character digit to its integer equivalent. - Verification method: The
printBitRepresentation()function lets you confirm the bitset is working. For example, inputting10.0.0.1will output00001010.00000000.00000000.00000001. - Input validation note: Your current parser assumes valid IP inputs. For robustness, you might want to add checks later (like ensuring octets are between 0-255, no non-digit characters, etc.), but that's separate from the bitset task.
Alternative: Initialize in a Separate Loop
If you prefer to separate parsing and bitset setup, you can add this loop at the end of your constructor (after parsing all octets into arr):
for(int i = 0; i < 4; ++i){ bits[i] = std::bitset<8>(arr[i]); }
This is equally effective—pick whichever style fits your coding preference.
内容的提问来源于stack exchange,提问作者Nagato

