Search code examples
c++constructoripv4bitset

Bitset Initializing in C++


class Address {

    private :

        unsigned char arr[4] = {0};
        bitset<8>  bits[4];

    public :

        Address(){
            char  ip[50];
            char temp[4];
            cout <<"Enter your IP ADDRESS";
            cin >>ip;
            int i;
            int k=0;
            for(i=0;ip[i]!='\0';i++){

               if(ip[i]!='.') arr[k]=arr[k]*10 + (ip[i]-48);
               else k++;

            //Easy PARSE
            }
        }
};

I need to implement an Address class for IPV4. When I call the constructor of my Address class I am taking-> parsing the input to an 8-bit array of 4, which is basically the 4 octets of IPV4. 255.255.255.255 For example. Now I need to convert it to a binary array of 4. I don't want to create an external binary converter for this. I am willing to implement it using a bitset. Now the issue is, I haven't found a bitset function which lets me initialize the bits(convert from decimal to bitset) apart from its constructor, which is called as soon as my Address class is called. I can do it by having 4 separate member pointers to type bitset<8> and allocating each in Address(), but that is very inelegant approach. Any ideas? :/


Solution

  • You can change the bitset using the assignment operator after the construction.

    This might be the part you are looking for:

    for(int i=0; i <4; i++) {
        bits[i] = bitset<8>(arr[i]);
    }