Java 如何将十六进制字符串直接转换为字节数组?
我想把字符串转换成十六进制,然后转换成字节数组。以下是我目前的代码:Java 如何将十六进制字符串直接转换为字节数组?,java,hex,bytearray,Java,Hex,Bytearray,我想把字符串转换成十六进制,然后转换成字节数组。以下是我目前的代码: public static void findKey(){ Cipher cipher; SecretKeySpec key; byte [] keyBytes; byte [] pt; byte [] ct; String plaintext = "Plaintxt"; ct = new byte [] {(byte)0x4A, (byte)0xC4, (byte)
public static void findKey(){
Cipher cipher;
SecretKeySpec key;
byte [] keyBytes;
byte [] pt;
byte [] ct;
String plaintext = "Plaintxt";
ct = new byte [] {(byte)0x4A, (byte)0xC4, (byte)0x55, (byte)0x3D, (byte)0xB3, (byte)0x37, (byte)0xCA, (byte)0xB3};
String ptHex = asciiToHex(plaintext);
System.out.println(ptHex);
pt = ptHex.getBytes();
printByteArray(pt);
}
我的转换为十六进制的方法很好,但是当我使用getBytes
时,它显然将其转换为16个字节,这不是我想要的。那只是一次尝试。以下是仅打印我的字符串以确保其正常工作,然后打印不正确的字节数组的输出:
506c61696e747874
[ 35 30 36 63 36 31 36 39 36 65 37 34 37 38 37 34 ]
-------------Key Found-------------
我想取50,6c,61等等,然后把它放到一个字节数组中,就像我对ct做的那样,比如0x50,0x6c,等等
这可能吗?它可能会帮助你
Byte.parseByte(string, 16);
检查
同时检查此项,它可能会对您有所帮助
Byte.parseByte(string, 16);
检查
同时检查此项尝试
byte[] getBytes(String s) {
byte[] a = new byte[s.length() / 2];
for (int i = 0; i < a.length; i++) {
a[i] = Byte.parseByte(s.substring(i * 2, i * 2 + 2), 16);
}
return a;
}
byte[]获取字节(字符串s){
字节[]a=新字节[s.length()/2];
for(int i=0;i
试试看
byte[]获取字节(字符串s){
字节[]a=新字节[s.length()/2];
for(int i=0;i
使用这个使用JDK API的单行程序:
byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();
这里有一个测试:
import java.nio.ByteBuffer;
public static void main(String[] args) throws Exception {
String chars= "506c61696e747874";
byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();
System.out.println(Arrays.toString(array));
}
输出:
[80, 108, 97, 105, 110, 116, 120, 116]
当然这里的输出是十进制的,但是值是正确的。使用这个使用JDK API的单行程序:
byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();
这里有一个测试:
import java.nio.ByteBuffer;
public static void main(String[] args) throws Exception {
String chars= "506c61696e747874";
byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();
System.out.println(Arrays.toString(array));
}
输出:
[80, 108, 97, 105, 110, 116, 120, 116]
当然,这里的输出是十进制的,但值是正确的。将十六进制转换为字节数组的简单java方法:
byte[] byteArray= new BigInteger(hexvalue, 2).toByteArray();
将十六进制转换为字节数组的简单java方法:
byte[] byteArray= new BigInteger(hexvalue, 2).toByteArray();
先生,你才是真正的男人。这正是我要找的。先生,你才是真正的男人。这正是我想要的。