Thank you for converting the IP address into a binary code. It mainly uses the stack for storage and converts the binary output. Although the function is implemented, I personally feel that it is not ideal and complicated. After all, this is the first time I have written this code and posted it. Please advise me!
# Include "Stack. H"
# Include <string>
# Include <iostream>
Using namespace STD;
Int main ()
{
Int A [32] = {0 };
Int B [32] = {0 };
Stack st;
Initstack (ST );
Cout <"enter an IP address in the format of 192.168.1.1" <Endl;
Char ch [16];
Cin> CH;
//////// Split the string
Char * tokenptr = strtok (CH, (const char *)".");
While (tokenptr)
{
Int J = atoi (tokenptr );
For (int K = 0; k <8; k ++)
{
Pushelem (St, J % 2 );
J = J/2;
}
Tokenptr = strtok (nullptr, (const char *)".");
}
Int I = 0;
While (St. Base! = ST. Top)
{
Popelem (St, a [I ++]);
}
////// Invert the data
Int JJ = 24;
Int K = 0;
For (; JJ <32; JJ ++)
B [k ++] = A [JJ];
For (JJ = 16; JJ <24; JJ ++)
B [k ++] = A [JJ];
For (JJ = 8; JJ <16; JJ ++)
B [k ++] = A [JJ];
For (JJ = 0; JJ <8; JJ ++)
B [k ++] = A [JJ];
For (int K = 0; k <32; k ++)
{
If (K % 8 = 0)
{
Cout <"";
}
Cout <B [k];
}
Return 1;
}
# Include "Stack. H"
# Include <stdlib. h>
# Define initsize 100
# Define increase 20
Bool initstack (stack & St)
{
St. base = new elemtype [initsize];
If (St. base = nullptr)
{
Return 0;
}
St. Top = ST. base;
St. size = initsize;
Return 1;
}
Void pushelem (stack & St, elemtype ELEM)
{
If (St. Top-St. base = ST. Size)
{
Elemtype * pelem = new elemtype [initsize + increase];
If (pelem = nullptr)
Exit (0 );
St. base = pelem;
St. Top = ST. Base + initsize;
St. Size + = initsize;
}
* St. Top ++ = ELEM;
}
Bool popelem (stack & St, elemtype & ELEM)
{
If (St. Top = ST. Base)
Return 0;
ELEM = * -- st. Top;
Return 1;
}
Convert an IP address to binary data