首页 > 代码库 > 将ip地址转成二进制数据
将ip地址转成二进制数据
小弟不才,谢了个 将ip地址转成二进制的代码。主要用了栈来存储,在输出二进制时做了转换,虽然实现了功能,个人感觉不是很理想,有些繁琐。毕竟是自己第一次写这个代码,贴上去,请大侠们指教!
#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<<"请输入一个IP地址,格式如:192.168.1.1"<<endl;
char ch[16];
cin>>ch;
/////////分割字符串
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++]);
}
///////倒置数据
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;
}
将ip地址转成二进制数据