Last active
August 29, 2015 14:01
-
-
Save kwon37xi/487be0d19922a64597f3 to your computer and use it in GitHub Desktop.
Java number / byte arary convert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
/** | |
* int 형과 byte[] 간의 변환. | |
* ByteBuffer 를 사용하는 방법 대신, bit operator를 사용하는 기법. | |
* | |
* Java는 기본적으로 BigEndian이다. | |
* | |
* 참조 | |
* - http://stackoverflow.com/questions/2383265/convert-4-bytes-to-int | |
* - http://nuridol.egloos.com/1629750 : ByteBuffer | |
*/ | |
public class NumberBytesUtils { | |
public static void main(String[] args) { | |
int num = 2892; | |
byte[] bytes = intToBytes(num); | |
System.out.println(num + " to bytes " + Arrays.toString(bytes)); | |
System.out.println("to num again : " + bytesToInt(bytes)); | |
} | |
public static byte[] intToBytes(int value) { | |
return new byte[]{ | |
(byte) (value >>> 24), | |
(byte) (value >>> 16), | |
(byte) (value >>> 8), | |
(byte) (value) | |
}; | |
} | |
public static int bytesToInt(byte[] bytes) { | |
int value = ((int)bytes[0] & 0xFF) << 24; | |
value += ((int)bytes[1] & 0xFF) << 16; | |
value += ((int)bytes[2] & 0xFF) << 8; | |
value += (int)bytes[3] & 0xFF; | |
return value; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
public void intToBytes() { | |
assertIntBytesConvert(0); | |
assertIntBytesConvert(1); | |
assertIntBytesConvert(-1); | |
assertIntBytesConvert(500); | |
assertIntBytesConvert(-500); | |
assertIntBytesConvert(Integer.MAX_VALUE); | |
assertIntBytesConvert(Integer.MIN_VALUE); | |
} | |
private void assertIntBytesConvert(final int value) { | |
byte[] bytes = intToBytes(value); | |
log.debug("int {} to bytes : {}", value, bytes); | |
assertThat(bytes).hasSize(4); // 32bit | |
assertThat(bytesToInt(bytes)).isEqualTo(value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment