#include <iostream> using namespace std; char* intToBin(int a) { char *str = (char *)malloc(8); memset(str, '0', 8); str[8] = '\0'; //cout << strlen(str) << endl; int i = 7; while (a && i >= 0) { //cout << i << endl; //cout << a % 2; str[i--] = (a % 2 + '0'); a /= 2; }; return str; } int binToInt(const char *str) { int ans = 0; for (int i = strlen(str) - 1; i >= 0; i--) { ans += (str[i] - '0') * (pow(2, strlen(str) - 1 - i)); } return ans; } int arr[4] = { 0 }; int fun(const char *str) { int k = 3; for (int j = strlen(str) - 1, m = 1; j >= 0; j--) { if (str[j] == '.') { m = 1; k--; continue; } arr[k] += m * (str[j] - '0'); m = m * 10; } /*cout << arr[0] << endl; cout << arr[1] << endl; cout << arr[2] << endl; cout << arr[3] << endl;*/ //cout << strlen(str) << endl; return 0; } int main() { const char *s = "127.0.0.1"; fun(s); char *str = (char *)malloc(33); memset(str, '\0', 33); for (int i = 0; i < 4; i++) { //cout << intToBin(arr[i]) << endl; memcpy(str + (i * 8), intToBin(arr[i]), 8); } cout << str << endl; cout << binToInt(str) << endl; //cout << fun(s) << endl; //cout << intToBin(127) << endl; return 0; }