0 / 0 / 0
Регистрация: 04.08.2016
Сообщений: 79
1

Написать функции для преобразования IP адреса из dot-decimal нотации в int и из int в dot-decimal нотацию

24.08.2016, 21:10. Показов 3149. Ответов 3
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
IP-адрес - это четверка a.b.c.d, где a, b, c, d целые числа из интервала [0,255]. Требуется написать функции encode и decode:

C++
1
2
unsigned int encode(const std::string& ipAddress);
std::string decode(unsigned int code);
Первая функция превращает ай-пи адрес в четырех байтовое число. Функция decode выполняет обратный процесс. Неважно, как написаны функции. Главное, чтобы encode(decode(x)) было равно х для любого без знакового целого х; и чтобы decode(encode(strIp)) было равно strIp для любой строки, представляющей собой айпи адрес.

C++
1
2
std::cout << decode(encode(“125.0.0.4”)) ; //prints 125.0.0.4
std::cout << encode(decode(19)) ; //prints 19
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
24.08.2016, 21:10
Ответы с готовыми решениями:

Как грамотно перемножить Decimal и Int
Как грамотно перемножить Decimal и Int?

Немогу установить значения с запятой Int,Decimal,Float
Делаю простую страницу с оценками, поставил в базе данных notes таблице notes, поле: id ...

Как в панде сконвертировать строку в число? - astype(int), to_numeric, decimal не срабатывают
Есть числа через точку в списке словарей с неопределенным заголовком (их много, все долго...

Перевести число типа int в decimal (к примеру 4 => 0.0001) 4 - кол-во знаков после запятой
public static decimal intToDecimal(int precision) { string result = &quot;0,&quot;; for (int i...

3
1 / 1 / 3
Регистрация: 24.08.2016
Сообщений: 18
25.08.2016, 12:01 2
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
unsigned int encode(const std::string& ipAddress)
{
  unsigned int result = 0;
  string iP = ipAddress;
  unsigned char data =0;
  string num;
  while(iP.size())
  {
    if(iP[iP.size()-1] == '.')
    {
      data = atoi(num.c_str());
      result |=data;
      result<<8;
      iP.erase(iP.size()-1,1);
      data = 0;
      num.clear();
    } 
    else
    {
     num+=iP[iP.size()-1];
     iP.erase(0,1);
     
     }
  }
  data = atoi(num.c_str());
  result |=data;
 return result ;
}
 
 
std::string decode(unsigned int code)
{
 std::string result;
 unsigned char data =0;
 
 data|= code;
 result+=itoa(data);
 result+='.';
 
 code>>8;
 data = 0;
 data|= code;
 result+=itoa(data);
 result+='.';
 
 code>>8;
 data = 0;
 data|= code;
 result+=itoa(data);
 result+='.';
 
 code>>8;
 data = 0;
 data|= code;
 result+=itoa(data);
 
return result;
}
0
6045 / 2160 / 753
Регистрация: 10.12.2010
Сообщений: 6,005
Записей в блоге: 3
25.08.2016, 14:24 3
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#include <iostream>
#include <sstream>
#include <vector>
#include <stdexcept>
 
unsigned int encode(const std::string& ipAddress);
std::string decode(const unsigned int code);
 
namespace 
{
 
std::vector<std::string> Split(const std::string& str, const char delim);
std::vector<std::string>& Split(const std::string& str, const char delim, std::vector<std::string>& elems);
int StringToInt(const std::string& str);
std::vector<unsigned char>& ParseOctets(const std::string& ipAddress, std::vector<unsigned char>& octets);
std::vector<unsigned char>& ExtractOctets(const unsigned int ip, std::vector<unsigned char>& octets);
std::string ConstructIpFromOctets(const std::vector<unsigned char>& octets);
 
std::vector<std::string> Split(const std::string& str, const char delim)
{
    std::vector<std::string> elems;
    
    Split(str, delim, elems);
    
    return elems;
}
 
std::vector<std::string>& Split(const std::string& str, const char delim, std::vector<std::string>& elems)
{
    std::stringstream stream(str);
    
    std::string item;
    
    while (std::getline(stream, item, delim))
    {
        if (!item.empty()) elems.push_back(item);
    }
    
    return elems;
}
 
int StringToInt(const std::string& str)
{
    int value = 0;
    
    std::stringstream stream(str);
    
    stream >> value;
    
    return value;
}
 
std::vector<unsigned char>& ParseOctets(const std::string& ipAddress, std::vector<unsigned char>& octets)
{   
    std::stringstream exceptionStream;
    
    bool errorOccurred = false;
    
    do
    {
        const size_t maxIpAddressLength = 15;
        const size_t minIpAddressLength = 7;
        
        if ((ipAddress.length() < minIpAddressLength) || (ipAddress.length() > maxIpAddressLength))
        {
            exceptionStream << "Invalid IP-address length. Expected: ["<< minIpAddressLength <<
                " - " << maxIpAddressLength << "], actual: " << ipAddress.length() << std::endl;
                
            errorOccurred = true;
            break;
        }
                
        std::vector<std::string> octetStrings = Split(ipAddress, '.');
        
        const size_t allowedOctetCount = 4;
        
        if (octetStrings.size() != allowedOctetCount)
        {
            exceptionStream << "Invalid octet count. Expected: " << allowedOctetCount << ", actual:" <<
                octetStrings.size() << std::endl;
            
            errorOccurred = true;
            break;
        }
        
        const int maxOctetValue = 255;
        
        std::vector<std::string>::size_type i = 0;
        
        while ((i != octetStrings.size()) && !errorOccurred)
        {
            int temp = StringToInt(octetStrings[i]);
        
            if ((temp < 0) || (temp > maxOctetValue))
            {
                exceptionStream << "Invalid octet #" << (i + 1) << ". Expected: [0 - " << maxOctetValue <<
                    "], actual: '" << temp << "'" << std::endl;
                    
                errorOccurred = true;
            }
            else octets.push_back((unsigned char)temp);
            
            i++;
        }
    }
    while (false);
    
    if (errorOccurred) throw std::invalid_argument(exceptionStream.str());
    
    return octets;
}
 
std::vector<unsigned char>& ExtractOctets(const unsigned int ip, std::vector<unsigned char>& octets)
{
    const unsigned char maxOffset = 24;
    
    unsigned char octet;
    
    for (unsigned char offset = 0; offset <= maxOffset; offset = offset + 8)
    {
        octet = (ip >> offset) & 0xFF;
        octets.push_back(octet);
    }
    
    return octets;
}
 
std::string ConstructIpFromOctets(const std::vector<unsigned char>& octets)
{
    std::stringstream stream;
    
    stream << (int)octets[3] << "." << (int)octets[2] << "." << (int)octets[1] << "." << (int)octets[0];
    
    return stream.str();
}
 
} // end namespace
 
unsigned int encode(const std::string& ipAddress)
{
    std::vector<unsigned char> octets;
 
    ParseOctets(ipAddress, octets);
    
    unsigned int result = (octets[0] * 16777216) + (octets[1] * 65536) + (octets[2] * 256) + octets[3];
    
    return result;
}
 
std::string decode(const unsigned int code)
{
    std::string ipAddress;
    
    std::vector<unsigned char> octets;
    
    ExtractOctets(code, octets);
    
    ipAddress = ConstructIpFromOctets(octets);
    
    return ipAddress;
}
 
int main(void)
{
    unsigned int ip;
    
    try
    {
        ip = encode("192.168.0.1");
        
        std::cout << ip << std::endl;
    }
    catch (const std::invalid_argument& e)
    {
        std::cout << e.what() << std::endl;
    }
    
    std::cout << decode(2449469064) << std::endl;
    
    std::cout << decode(encode("64.52.0.122")) << std::endl;
    
    return 0;
}
0
Эксперт С++
3224 / 1751 / 436
Регистрация: 03.05.2010
Сообщений: 3,867
25.08.2016, 16:44 4
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//IP-адрес - это четверка a.b.c.d, где a, b, c, d целые числа
//из интервала [0,255]. Требуется написать функции encode и decode:
 
//unsigned int encode(const std::string& ipAddress);
//std::string decode(unsigned int code);
 
//Первая функция превращает ай-пи адрес в четырех байтовое число.
//Функция decode выполняет обратный процесс. Неважно, как написаны функции.
//Главное, чтобы encode(decode(x)) было равно х для любого без знакового
//целого х; и чтобы decode(encode(strIp)) было равно strIp для любой строки,
//представляющей собой айпи адрес.
 
//std::cout << decode(encode(“125.0.0.4”)) ; //prints 125.0.0.4
//std::cout << encode(decode(19)) ; //pri
///////////////////////////////////////////////////////////////////////////////
#include <bitset>
#include <climits>
#include <iostream>
#include <sstream>
#include <string>
///////////////////////////////////////////////////////////////////////////////
const   int     NUMBERS_PER_ADDRESS     {4};
const   char    POINT_SYMB              {'.'};
///////////////////////////////////////////////////////////////////////////////
typedef std::string                     T_ip_adr;
typedef unsigned                        T_uint;
typedef std::bitset     < CHAR_BIT  >   T_byte_bitset;
///////////////////////////////////////////////////////////////////////////////
T_uint  encode( T_ip_adr    const   &   ip_adr )
{
    T_uint              res     {};
    std::istringstream  ssin    ( ip_adr );
    T_uint              val     {};
    char                delim   {};
 
    do
    {
        ssin    >>      val;
        res     <<=     CHAR_BIT;
        res     |=      val;
    }
    while( ssin >> delim );
 
    return  res;
}
///////////////////////////////////////////////////////////////////////////////
T_ip_adr    decode( T_uint   code )
{
    T_ip_adr    res_adr;
 
    for( int  i{}; i < NUMBERS_PER_ADDRESS; ++i )
    {
        res_adr     =       std::to_string
                                (
                                    T_byte_bitset( code ).to_ulong()
                                )
 
                        +   POINT_SYMB
                        +   res_adr;
 
        code        >>=     CHAR_BIT;
    }//for
 
    res_adr.pop_back();
    return  res_adr;
}
///////////////////////////////////////////////////////////////////////////////
int     main()
{
    std::cout   <<  decode  (
                                encode("125.0.0.4")
                            )
 
                <<  std::endl
 
                <<  encode  (
                                decode(19)
                            )
 
                <<  std::endl;
}
0
25.08.2016, 16:44
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.08.2016, 16:44
Помогаю со студенческими работами здесь

Не работает запрос с одинаковыми типами данных c# decimal, SQL Server Decimal(18,2)
Здравствуйте, не понимаю почему не проходит запрос на бд, с одинаковыми типами данныхDecimal(18,2)...

Какая из этих функций int Q(int w) int W(int y,int u,int i) сработает быстрее?
Если есть 2 функции(простые или перегруженные) к примеру Q(int w) int W(int y,int u,int i)или int...

Ошибка: cannot convert 'int (*)[50]' to 'int*' for argument '1' to 'void vvod2m(int*, int*, int*, char)'Х2
Матрицы An1*m1 и Bn2*m2 вводить с клавиатуры (размерности &gt;3, m1=n2). Выполнять через подпрограммы....

Graphviz. Ошибка "dot: can't open dot"
Здравствуйте. Пытаюсь разобраться с Graphviz для визуализации графа, в интернете был найден такой...

Блин, для ЧЕГО НУЖНА Функция CREATE TABLE invoice( inv_id INT AUTO_INCREMENT NOT NULL , usr_id INT NOT NULL , prod_id INT NOT NULL , quantity INT NOT
Погуглив, так и не смог толком понять. Есть тут ГУРУ по mysql Которые могут на пальцах или на...

Не удается неявно преобразовать тип "decimal" в "int"
Здравствуйте! Помогите решить эту закавыку! ((( private void button1_Click(object sender,...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru