「testing123」のような文字列をJavaで16進形式に変換しようとしています。私は現在BlueJを使用しています。
そして、それを元に戻すために、それは逆方向を除いて同じことですか?
16 進数が常に 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
16 進数にエンコードする数値は、UTF-8 などの文字のエンコードを表す必要があります。したがって、最初に文字列をそのエンコーディングで文字列を表す byte[] に変換してから、各バイトを 16 進数に変換します。
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 はデフォルトで含まれていないため、これにより および newer で少し余分な問題が発生します。参考までに、この 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 バイト文字の 16 進値を必ずしも取得できるとは限りません。実際に必要なものが 16 進ビューアーに相当するものである場合は、文字に直接アクセスする必要があります。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
16 進数の整数値を取得するには
//hex like: 0xfff7931e to int
int hexInt = Long.decode(hexString).intValue();
私はこのようなものを提案し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());
}
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();
逆方向 (16 進数から文字列) にするには、次を使用できます。
public String hexToString(String hex) {
return new String(new BigInteger(hex, 16).toByteArray());
}
最初に getBytes() 関数を使用してバイトに変換し、次に this を使用して 16 進数に変換します。
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();
}
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);
}
}
ずっといい:
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);
}
さまざまなアプローチとライブラリを比較するいくつかのベンチマークを次に示します。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 の単一のクラス ファイルにあります。依存関係ツリーに別のライブラリが必要ない場合は、自由にコピーして貼り付けてください。また、Gradle と Bintray プラグインを使用して複数のリリース ターゲットを公開する方法を理解できるまで、Java 9 jar としてのみ利用できることにも注意してください。
new BigInteger(1, myString.getBytes(/*YOUR_CHARSET?*/)).toString(16)