0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

IPv6アドレスからプレフィックス長とIPv6アドレス部分を分けて2進数にする方法

Posted at
Main.java
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main  {
    public static void main(String[] args) throws Exception {
        String ipv6WithCIDR = "2001:1111:2222:abcd::/64"; // 任意のIPv6アドレス

        // プレフィックスを分離
        String[] parts = ipv6WithCIDR.split("/");
        String ipv6Address = parts[0]; // IPv6アドレス部分
        int prefixLength = Integer.parseInt(parts[1]); // プレフィックス長

        try {
            InetAddress inetAddress = InetAddress.getByName(ipv6Address);
            byte[] ipBytes = inetAddress.getAddress();

            StringBuilder binaryString = new StringBuilder();
            for (byte b : ipBytes) {
                // 各バイトを2進数に変換して、ゼロパディングを行う
                String binary = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
                binaryString.append(binary).append(" "); // スペースで区切る
            }

            // プレフィックス部分を2進数で表示
            StringBuilder prefixBinary = new StringBuilder();
            for (int i = 0; i < 8; i++) {
                if (i < prefixLength / 16) {
                    // 完全な16ビットを追加
                    prefixBinary.append(binaryString.substring(i * 9, (i + 1) * 9 - 1)); // 9文字目はスペースを除く
                } else if (i == prefixLength / 16) {
                    // 部分的な16ビットを追加
                    String partialBinary = binaryString.substring(i * 9, (i + 1) * 9 - 1);
                    prefixBinary.append(partialBinary.substring(0, prefixLength % 16));
                }
            }

            System.out.println("IPv6アドレス: " + ipv6WithCIDR);
            System.out.println("全体の2進数表示: " + binaryString.toString().trim());
            System.out.println("プレフィックスの2進数表示: " + prefixBinary.toString().trim());
        } catch (UnknownHostException e) {
            System.out.println("無効なIPv6アドレス: " + ipv6Address);
        }
    }
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?