본문 바로가기
→ 개발/JAVA

[JAVA] int, long, short GetBytes()

by 벅스쭌 2020. 4. 29.
반응형

자바에는 C#에서의 BitConverter.GetBytes()가 없다.

그래서 또 만들어줘야 한다.

 

public static byte[] intConvertBytes(int value) throws Exception //4byte
{
byte[] tmpBuff = null;
try
{
ByteBuffer buff = ByteBuffer.allocate(Integer.BYTES);
buff.putInt(value);
tmpBuff = buff.array();
}
catch(Exception err)
{
throw new Exception("MusProtoUtility.java-longIpConvertBytes()", err);
}
return tmpBuff;
}

public static int bytesConvertInt(byte[] buff) throws Exception
{
int value = 0;
try
{
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.put(buff);
buffer.flip();
value = buffer.getInt();
}
catch(Exception err)
{
throw new Exception("MusProtoUtility.java-bytesConvertInt()", err);
}
return value;
}

public static byte[] shortConvertBytes(short value) throws Exception //2byte
{
byte[] tmpBuff = null;
try
{
ByteBuffer buff = ByteBuffer.allocate(Short.BYTES);
buff.putShort(value);
tmpBuff = buff.array();
}
catch(Exception err)
{
throw new Exception("MusProtoUtility.java-shortConvertBytes()", err);
}
return tmpBuff;
}

public static short bytesConvertShort(byte[] buff) throws Exception
{
short value = 0;
try
{
ByteBuffer buffer = ByteBuffer.allocate(Short.BYTES);
buffer.put(buff);
buffer.flip();
value = buffer.getShort();
}
catch(Exception err)
{
throw new Exception("MusProtoUtility.java-bytesConvertShort()", err);
}
return value;
}

반응형