angio 0 Share Posted January 7, 2021 I was curious if anyone has some other ideas to send/receive an integer without using a wrapper-class for OutputStream/InputStream public int readInt() throws IOException { int number = 0; byte[] bytes = new byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = (byte) inputStream.read(); } for (int i = 3; i >= 0; i--) { byte tmp = bytes[i]; for (int j = 7; j >= 0; j--) { if (((tmp >> j) & 1) == 1) number |= 1 << (j + (i * 8)); } } return number; } public void send(int integer) throws IOException { synchronized (lock) { byte[] split = new byte[4]; for (int i = 0; i < split.length; i++) { split[i] = (byte) ((integer >> (i * 8)) & 255); } outputStream.write(OpCode.INTEGER.ordinal()); outputStream.write(split); outputStream.flush(); } } Link to comment Share on other sites More sharing options...
Neffarion 485 Share Posted January 8, 2021 17 hours ago, angio said: I was curious if anyone has some other ideas to send/receive an integer without using a wrapper-class for OutputStream/InputStream public int readInt() throws IOException { int number = 0; byte[] bytes = new byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = (byte) inputStream.read(); } for (int i = 3; i >= 0; i--) { byte tmp = bytes[i]; for (int j = 7; j >= 0; j--) { if (((tmp >> j) & 1) == 1) number |= 1 << (j + (i * 8)); } } return number; } public void send(int integer) throws IOException { synchronized (lock) { byte[] split = new byte[4]; for (int i = 0; i < split.length; i++) { split[i] = (byte) ((integer >> (i * 8)) & 255); } outputStream.write(OpCode.INTEGER.ordinal()); outputStream.write(split); outputStream.flush(); } } Do you want to work solely with bitwise operations? Because otherwise you can use the ByteBuffer class. Especially for the readInt ByteBuffer.wrap(byteArr).getInt() Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.