java

ByteBuffer 객체 생성 및 크기 용량 할당

주피터0410 2023. 8. 11. 10:12

putLong() / putDouble() / put() 메소드를 이용하여 ByteBuffer.allocate(8) 크기만큼 용량을 할당

 

	public static void main(String[] args) throws UnsupportedEncodingException {

		// 8 -37 -103 -69 -106 -98 18 20
		long str1 = 638272803167932948L;
		byte[] bytes1 = ByteBuffer.allocate(8).putLong(str1).array();

		for (int i = 0; i < bytes1.length; i++) {
			System.out.println(bytes1[i]);
		}

		System.out.println("----------------------------------------");
		
		// 64 106 13 -62 -113 92 40 -10
		double str2 = 208.43;
		byte[] bytes2 = ByteBuffer.allocate(8).putDouble(str2).array();

		for (int i = 0; i < bytes2.length; i++) {
			System.out.println(bytes2[i]);
		}
        
		System.out.println("----------------------------------------");

		String str = "test";
		byte[] info = str.getBytes("utf-8");
		byte[] bytes = ByteBuffer.allocate(9).put(info).array();

		for (int i = 0; i < bytes.length; i++) {
			System.out.println(bytes[i]);
		}
	}