아무거나

문자열을 Hex(=16진수)로 변환하는 방법 (String To Hex) 본문

Java/Java

문자열을 Hex(=16진수)로 변환하는 방법 (String To Hex)

전봉근 2019. 1. 7. 17:17
반응형

Hexadecimal: 컴퓨터 분야에서 숫자를 표현하기 위해 사용하는 진법 방식중에 하나이다. 이것은 Hexadecimal 또는 Hex라고 불린다.

-> 16진수 (16을 기수로 하는 번호체계를 말한다.)


이러한 헥사코드를 Java를 이용하여 문자열 -> Hex, Hex -> 문자열을 변환하는 방법을 알아보자.


import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class ExampleMain {

public static void main(String[] args) throws Exception {
String testStr = "bkjeon1614";

HexConverter hexConverter = new HexConverter();
String stringToHex = hexConverter.getStringToHex(testStr);
String hexToString = hexConverter.getHexToString(stringToHex);

System.out.println("String To Hex: " + stringToHex);
System.out.println("Hex To String: " + hexToString);
}

}

// 코드 변환
class HexConverter {
// String to Hex
public String getStringToHex(String testStr) throws UnsupportedEncodingException {
byte[] testBytes = testStr.getBytes("UTF-8");
return DatatypeConverter.printHexBinary(testBytes);
}

// Hex to String
public String getHexToString(String testHex) throws UnsupportedEncodingException, DecoderException {
// https://mvnrepository.com/artifact/commons-codec/commons-codec/1.10
byte[] testBytes = Hex.decodeHex(testHex.toCharArray());
return new String(testBytes, "UTF-8");
}
}


반응형
Comments