I have a base64 encode want convert to utf8 string ,use php mb_convert_encoding convert is normal,code by:
$p=base64_decode("DFknU2sALQAyADAAMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==");
echo mb_convert_encoding(substr($p, 1, 12), 'utf8', 'utf-16');
echo "n";
How to convert to utf8 string in java.
String str = "0C5927536B002D003200300032000000000000000000000000000000000000000000000000000000";
String b = hexStringToString(str); // parse hexadecimal
String string = new String(b.getBytes("UTF-8"), "UTF-16");
System.out.println(string); // no
I want result is :
大卫-202
Advertisement
Answer
Use Hex class in commons-codec library.
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>latest</version> </dependency>
use import org.apache.commons.codec.binary.Hex; and then:
String str = "0C5927536B002D003200300032000000000000000000000000000000000000000000000000000000"; byte[] bytes = Hex.decodeHex(str.toCharArray()); System.out.println(new String(bytes, "UTF-8"));
Since in your PHP code the string is selected from byte 1 (substr($p, 1, 12)) you need to remove byte 1 when converting in java code. So:
String str = "0C5927536B002D003200300032000000000000000000000000000000000000000000000000000000"; byte[] bytes = Hex.decodeHex(str.toCharArray()); String str2 = new String(bytes, 1, 12, "UTF-16"); System.out.println(str2);