[英]Converting A String To Hexadecimal In Java
我正在嘗試將類似“testing123”的字符串轉換為java中的十六進制形式。 我目前正在使用 BlueJ。
並且將其轉換回來,除了向后之外,它是一樣的嗎?
這是將其轉換為十六進制的簡短方法:
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
為確保十六進制長度始終為40個字符,BigInteger必須為正數:
public String toHex(String arg) {
return String.format("%x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
import org.apache.commons.codec.binary.Hex;
...
String hexString = Hex.encodeHexString(myString.getBytes(/* charset */));
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html
您編碼為十六進制的數字必須代表字符的某些編碼,例如UTF-8。 因此,首先將String轉換為表示該編碼中的字符串的byte [],然后將每個字節轉換為十六進制。
public static String hexadecimal(String input, String charsetName) throws UnsupportedEncodingException {
if (input == null) throw new NullPointerException();
return asHex(input.getBytes(charsetName));
}
private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
public static String asHex(byte[] buf)
{
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
使用DatatypeConverter.printHexBinary()
:
public static String toHexadecimal(String text) throws UnsupportedEncodingException
{
byte[] myBytes = text.getBytes("UTF-8");
return DatatypeConverter.printHexBinary(myBytes);
}
用法示例:
System.out.println(toHexadecimal("Hello StackOverflow"));
打印:
48656C6C6F20537461636B4F766572666C6F77
注意 :這會導致Java 9
及更新版本出現一些額外的麻煩,因為默認情況下不包含API。 供參考,例如,請參閱此 GitHub
問題。
這是另一種解決方案
public static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for(int i = 0; i < ba.length; i++)
str.append(String.format("%x", ba[i]));
return str.toString();
}
public static String fromHexString(String hex) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
}
return str.toString();
}
所有基於String.getBytes()的答案都涉及根據Charset對字符串進行編碼 。 您不一定得到構成字符串的2字節字符的十六進制值。 如果您真正想要的是十六進制查看器,那么您需要直接訪問這些字符。 這是我在代碼中用於調試Unicode問題的函數:
static String stringToHex(String string) {
StringBuilder buf = new StringBuilder(200);
for (char ch: string.toCharArray()) {
if (buf.length() > 0)
buf.append(' ');
buf.append(String.format("%04x", (int) ch));
}
return buf.toString();
}
然后,stringToHex(“testing123”)將為您提供:
0074 0065 0073 0074 0069 006e 0067 0031 0032 0033
我會建議像這樣的東西,其中str
是你的輸入字符串:
StringBuffer hex = new StringBuffer();
char[] raw = tokens[0].toCharArray();
for (int i=0;i<raw.length;i++) {
if (raw[i]<=0x000F) { hex.append("000"); }
else if(raw[i]<=0x00FF) { hex.append("00" ); }
else if(raw[i]<=0x0FFF) { hex.append("0" ); }
hex.append(Integer.toHexString(raw[i]).toUpperCase());
}
獲取十六進制的Integer值
//hex like: 0xfff7931e to int
int hexInt = Long.decode(hexString).intValue();
轉換為十六進制代碼的字母和十六進制代碼的字母。
String letter = "a";
String code;
int decimal;
code = Integer.toHexString(letter.charAt(0));
decimal = Integer.parseInt(code, 16);
System.out.println("Hex code to " + letter + " = " + code);
System.out.println("Char to " + code + " = " + (char) decimal);
byte[] bytes = string.getBytes(CHARSET); // you didn't say what charset you wanted
BigInteger bigInt = new BigInteger(bytes);
String hexString = bigInt.toString(16); // 16 is the radix
你可以在這一點返回hexString
,但需要刪除前導空字符,如果第一個字節小於16,結果將有一個奇數長度。如果你需要處理這些情況,你可以添加一些額外的用0填充的代碼:
StringBuilder sb = new StringBuilder();
while ((sb.length() + hexString.length()) < (2 * bytes.length)) {
sb.append("0");
}
sb.append(hexString);
return sb.toString();
換句話說(十六進制到字符串),你可以使用
public String hexToString(String hex) {
return new String(new BigInteger(hex, 16).toByteArray());
}
首先使用getBytes()函數將其轉換為字節,然后將其轉換為十六進制使用:
private static String hex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<bytes.length; i++) {
sb.append(String.format("%02X ",bytes[i]));
}
return sb.toString();
}
使用來自多個線程的多人幫助..
我知道這已經得到解答,但我想為我遇到同樣情況的任何其他人提供一個完整的編碼和解碼方法..
這是我的編碼和解碼方法..
// Global Charset Encoding
public static Charset encodingType = StandardCharsets.UTF_8;
// Text To Hex
public static String textToHex(String text)
{
byte[] buf = null;
buf = text.getBytes(encodingType);
char[] HEX_CHARS = "0123456789abcdef".toCharArray();
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
// Hex To Text
public static String hexToText(String hex)
{
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2)
{
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
String st = new String(data, encodingType);
return st;
}
沒有外部庫的一行 HEX 編碼/解碼(Java 8 及更高版本):
編碼:
String hexString = inputString.chars().mapToObj(c ->
Integer.toHexString(c)).collect(Collectors.joining());
解碼:
String decodedString = Stream.iterate(0, i -> i+2)
.limit(hexString.length()/2 + Math.min(hexString.length()%2,1))
.map(i -> "" + (char)Integer.parseInt("" + hexString.charAt(i) + hexString.charAt(i+1),16))
.collect(Collectors.joining());
import java.io.*;
import java.util.*;
public class Exer5{
public String ConvertToHexadecimal(int num){
int r;
String bin="\0";
do{
r=num%16;
num=num/16;
if(r==10)
bin="A"+bin;
else if(r==11)
bin="B"+bin;
else if(r==12)
bin="C"+bin;
else if(r==13)
bin="D"+bin;
else if(r==14)
bin="E"+bin;
else if(r==15)
bin="F"+bin;
else
bin=r+bin;
}while(num!=0);
return bin;
}
public int ConvertFromHexadecimalToDecimal(String num){
int a;
int ctr=0;
double prod=0;
for(int i=num.length(); i>0; i--){
if(num.charAt(i-1)=='a'||num.charAt(i-1)=='A')
a=10;
else if(num.charAt(i-1)=='b'||num.charAt(i-1)=='B')
a=11;
else if(num.charAt(i-1)=='c'||num.charAt(i-1)=='C')
a=12;
else if(num.charAt(i-1)=='d'||num.charAt(i-1)=='D')
a=13;
else if(num.charAt(i-1)=='e'||num.charAt(i-1)=='E')
a=14;
else if(num.charAt(i-1)=='f'||num.charAt(i-1)=='F')
a=15;
else
a=Character.getNumericValue(num.charAt(i-1));
prod=prod+(a*Math.pow(16, ctr));
ctr++;
}
return (int)prod;
}
public static void main(String[] args){
Exer5 dh=new Exer5();
Scanner s=new Scanner(System.in);
int num;
String numS;
int choice;
System.out.println("Enter your desired choice:");
System.out.println("1 - DECIMAL TO HEXADECIMAL ");
System.out.println("2 - HEXADECIMAL TO DECIMAL ");
System.out.println("0 - EXIT ");
do{
System.out.print("\nEnter Choice: ");
choice=s.nextInt();
if(choice==1){
System.out.println("Enter decimal number: ");
num=s.nextInt();
System.out.println(dh.ConvertToHexadecimal(num));
}
else if(choice==2){
System.out.println("Enter hexadecimal number: ");
numS=s.next();
System.out.println(dh.ConvertFromHexadecimalToDecimal(numS));
}
}while(choice!=0);
}
}
new BigInteger(1, myString.getBytes(/*YOUR_CHARSET?*/)).toString(16)
好多了:
public static String fromHexString(String hex, String sourceEncoding ) throws IOException{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
int _start=0;
for (int i = 0; i < hex.length(); i+=2) {
buffer[_start++] = (byte)Integer.parseInt(hex.substring(i, i + 2), 16);
if (_start >=buffer.length || i+2>=hex.length()) {
bout.write(buffer);
Arrays.fill(buffer, 0, buffer.length, (byte)0);
_start = 0;
}
}
return new String(bout.toByteArray(), sourceEncoding);
}
將字符串轉換為十六進制 :
public String hexToString(String hex) {
return Integer.toHexString(Integer.parseInt(hex));
}
絕對這是簡單的方法。
以下是一些比較不同方法和庫的基准 。 Guava在解碼時勝過Apache Commons Codec。 Commons Codec在編碼時擊敗Guava。 JHex在解碼和編碼方面都勝過它們。
String hexString = "596f752772652077656c636f6d652e";
byte[] decoded = JHex.decodeChecked(hexString);
System.out.println(new String(decoded));
String reEncoded = JHex.encode(decoded);
一切都在JHex的單個類文件中 。 如果您不想在依賴關系樹中使用另一個庫,請隨意復制粘貼。 另請注意,它只能用作Java 9 jar,直到我可以弄清楚如何使用Gradle和Bintray插件發布多個發布目標。
將String轉換為十六進制表示法的簡便方法是:
public static void main(String... args){
String str = "Hello! This is test string.";
char ch[] = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ch.length; i++) {
sb.append(Integer.toHexString((int) ch[i]));
}
System.out.println(sb.toString());
}
檢查此解決方案的String為十六進制,十六進制為String,反之亦然
public class TestHexConversion {
public static void main(String[] args) {
try{
String clearText = "testString For;0181;with.love";
System.out.println("Clear Text = " + clearText);
char[] chars = clearText.toCharArray();
StringBuffer hex = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
hex.append(Integer.toHexString((int) chars[i]));
}
String hexText = hex.toString();
System.out.println("Hex Text = " + hexText);
String decodedText = HexToString(hexText);
System.out.println("Decoded Text = "+decodedText);
} catch (Exception e){
e.printStackTrace();
}
}
public static String HexToString(String hex){
StringBuilder finalString = new StringBuilder();
StringBuilder tempString = new StringBuilder();
for( int i=0; i<hex.length()-1; i+=2 ){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
finalString.append((char)decimal);
tempString.append(decimal);
}
return finalString.toString();
}
輸出如下:
Clear Text = testString For; 0181; with.love
十六進制文字= 74657374537472696e6720466f723b303138313b776974682e6c6f7665
Decoded Text = testString For; 0181; with.love
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.