angio 0 Share Posted January 7, 2021 (edited) 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(); } } Edited January 7, 2021 by angio Link to comment Share on other sites More sharing options...
Neffarion 469 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
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now