I can not understand why negative numbers come to the print()
method, and I have to add 256
to them for the subsequent transfer to the binary system? How to avoid it, or how to work with it correctly?
public class Solution { public static void main(String[] args) { byte[] ip = new byte[]{(byte) 192, (byte) 168, 1, 2}; byte[] mask = new byte[]{(byte) 255, (byte) 255, (byte) 254, 0}; print(ip); //11000000 10101000 00000001 00000010 print(mask); //11111111 11111111 11111110 00000000 print(netAddress); //11000000 10101000 00000000 00000000 }; public static void print(byte[] bytes) { for (int i : bytes) { StringBuilder sb = new StringBuilder(); if (i < 0) i = (256 + i); // --- почему приходится использовать костыль? for (int j = 0; j < 8; j++) { sb.append(i % 2); i /= 2; } sb.reverse(); System.out.print(sb+ " "); } System.out.println(); }; }