Java에서 바이트 어레이 및 int 유형의 변환. 네트워크 프로그래밍 에서이 알고리즘은 가장 기본적인 알고리즘입니다. 우리는 소켓 전송에서 발신자가 보내고 수신 한 데이터가 모두 바이트 어레이이지만 int 유형은 4 바이트로 구성되어 있음을 알고 있습니다. 모양을 바이트 어레이로 변환하는 방법 및 길이 4의 바이트 배열을 int 유형으로 변환하는 방법. 아래에는 두 가지 방법이 있습니다.
public static byte [] int2byte (int res) {byte [] targets = new byte [4]; targets [0] = (byte) (res & 0xff); // 가장 낮은 비트 대상 [1] = (byte) ((res >> 8) & 0xff); // 2 차 낮은 비트 target [2] = (res >> 16) & 0xff) & 0xff); (바이트) (RES >>> 24); // 가장 높은 비트, 서명되지 않은 오른쪽 이동. 반환 대상; } public static int byte2int (byte [] res) {// 바이트 데이터는 24 비트로 왼쪽으로 왼쪽으로 0x? ((res [1] << 8) & 0xff00) // | 주변 또는 |를 나타냅니다 ((res [2] << 24) >>> 8) | (RES [3] << 24); 반환 대상; }두 번째 유형
public static void main (String [] args) {bytearrayoutputStream baos = 새로운 BytearRayoutputStream (); DataOutputStream dos = 새로운 DataOutputStream (BAOS); try {dos.writebyte (4); dos.writebyte (1); dos.writebyte (1); Dos.Writeshort (217); } catch (ioexception e) {e.printstacktrace (); } byte [] aa = baos.tobytearray (); BytearrayinputStream bais = 새로운 BytearrayinputStream (baos.tobytearray ()); datainputStream dis = new DatainputStream (BAIS); {system.out.println (dis.readbyte ()); System.out.println (dis.readbyte ()); System.out.println (dis.readbyte ()); System.out.println (dis.readshort ()); } catch (ioexception e) {e.printstacktrace (); } try {dos.close (); 드러내다(); } catch (ioexception e) {e.printstacktrace (); }}위의 기사는 내가 공유하는 모든 컨텐츠 인 Java (두 가지 방법)의 바이트 배열 및 int 유형의 변환을 기반으로합니다. 나는 그것이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.