Skip to content

Commit 4c700ba

Browse files
cpp: added int32toIPv4 kata solution
1 parent 27870e6 commit 4c700ba

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

cpp/codewars/int32toip.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
//https://www.codewars.com/kata/52e88b39ffb6ac53a400022e/
2+
#include <sstream>
3+
#include <iomanip>
4+
#include <iostream>
5+
#include <bitset>
6+
std::string uint32_to_ip(uint32_t ip){
7+
std::stringstream ss;
8+
auto const separator = ".";
9+
std::bitset<32> bits = std::bitset<32>(ip);
10+
auto fourth_octet = ((bits&std::bitset<32>(0x000000FF)) >> 0).to_ulong();
11+
auto third_octet = ((bits&std::bitset<32>(0x0000FF00)) >> 8).to_ulong();
12+
auto second_octet = ((bits&std::bitset<32>(0x00FF0000)) >> 16).to_ulong();
13+
auto first_octet = ((bits&std::bitset<32>(0xFF000000)) >> 24).to_ulong();
14+
ss<<first_octet<<separator<<second_octet<<separator<<third_octet<<separator<<fourth_octet;
15+
return ss.str();
16+
}

0 commit comments

Comments
 (0)