Converting int array to byte array

I am attempting to convert an array of ints to a byte array to store in a file which will later be read and converted back into an int array. these are my conversion methods:
public static byte[] intArrayToByteArray(int[] intArr) {
byte[] byteArr = new byte[intArr.length*4];
for (int i = 0; i < intArr.length; i++) {
int val = intArr[i];
byteArr[(i*4)] = (byte) (val >> 24);
byteArr[(i*4)+1] = (byte) (val >> 16);
byteArr[(i*4)+2] = (byte) (val >> 8);
byteArr[(i*4)+3] = (byte) (val);
}
return byteArr;
}
public static int[] byteArrayToIntArray(byte[] byteArr) {
int[] intArr = new int[byteArr.length/4];
for (int i = 0; i < intArr.length; i++) {
intArr[i] = (byteArr[i*4] & 0xFF << 24) | (byteArr[(i*4)+1] & 0xFF << 16) | (byteArr[(i*4)+2] & 0xFF << 8) | (byteArr[(i*4)+3] & 0xFF);
}
return intArr;
}
public static byte[] intArrayToByteArray(int[] intArr) {
byte[] byteArr = new byte[intArr.length*4];
for (int i = 0; i < intArr.length; i++) {
int val = intArr[i];
byteArr[(i*4)] = (byte) (val >> 24);
byteArr[(i*4)+1] = (byte) (val >> 16);
byteArr[(i*4)+2] = (byte) (val >> 8);
byteArr[(i*4)+3] = (byte) (val);
}
return byteArr;
}
public static int[] byteArrayToIntArray(byte[] byteArr) {
int[] intArr = new int[byteArr.length/4];
for (int i = 0; i < intArr.length; i++) {
intArr[i] = (byteArr[i*4] & 0xFF << 24) | (byteArr[(i*4)+1] & 0xFF << 16) | (byteArr[(i*4)+2] & 0xFF << 8) | (byteArr[(i*4)+3] & 0xFF);
}
return intArr;
}
7 Replies
JavaBot
JavaBotā€¢4d ago
āŒ› This post has been reserved for your question.
Hey @š“pothicon! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
š“pothicon
š“pothiconOPā€¢4d ago
this is a test I did to see if my methods work
No description
š“pothicon
š“pothiconOPā€¢4d ago
-2 billion is turning into -16 million not sure what i did wrong
dan1st
dan1stā€¢4d ago
try removing the & 0xFF or use parenthesis x & 0xFF << 24 is x & (0xFF << 24) but you want (x & 0xFF) << 24 same with the others
š“pothicon
š“pothiconOPā€¢4d ago
ah yep that was it thanks
JavaBot
JavaBotā€¢4d ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
JavaBot
JavaBotā€¢4d ago
Post Closed
This post has been closed by <@465515365108154380>.

Did you find this page helpful?