How to convert an IPv6 address to a binary string?
Example:
IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
Binary: 0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100
I want to do this in Java. Here is my failed attempt (I do not ask for a solution related to this attempt whatsoever):
Implemented in C++, where I am more familiar:
#include <iostream>
#include <string>
#define _BSD_SOURCE
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
std::string toBinary(unsigned long int decimalIpV6)
{
std::string r;
while(decimalIpV6!=0) {r=(decimalIpV6%2==0 ?"0":"1")+r; decimalIpV6/=2;}
return r;
}
unsigned long int ipV6toDecimal(std::string binaryString) {
struct sockaddr_in antelope;
inet_aton(binaryString.c_str(), &antelope.sin_addr); // store IP in antelope
// and this call is the same as the inet_aton() call, above:
antelope.sin_addr.s_addr = inet_addr(binaryString.c_str());
return antelope.sin_addr.s_addr;
}
int main() {
std::string ipv6 = "192.168.0.0";
unsigned long int ipv6decimal= ipV6toDecimal(ipv6);
std::cout << toBinary(ipv6decimal) << std::endl;
return 0;
}
which is buggy and produces a wrong result ("1010100011000000").
PS: There is an IPv6 to Binary calculator online, which might help you when testing.
Try this solution :
String ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String[] spl = ipv6.split(":");
String result = "", del = "";
for (String s : spl) {
result += del
+ String.format("%16s", new BigInteger(s, 16).toString(2)).replace(' ', '0');
del = " ";
}
System.out.println(result);
If you are using Java 8 you can use :
String result = Stream.of(ipv6.split(":"))
.map(s -> String.format("%16s", new BigInteger(s, 16).toString(2)).replace(' ', '0'))
.collect(Collectors.joining(" "));
Output
0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100