• 将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;
    }

    博客内容只为本人学习所感转载亦或自写,不足或错误之处请大家不吝赐教
  • 相关阅读:
    Linux系统命令与权限
    有关Linux目录相关内容
    Linux的命令以及基本使用
    操作系统的基本知识与Linux系统简介
    IT知识架构与操作系统简介
    windows下nginx支持php的配置
    提权操作函数
    c++内存中字节对齐问题详解 [ 转载 ]
    STL 容器效率的对比
    C++ 四种类型转换的介绍
  • 原文地址:https://www.cnblogs.com/niupan369/p/4043726.html
Copyright © 2020-2023  润新知