2
4

1 回答 1

8
public class UseTheForce {
    public static void main(final String[] args)
        throws java.io.UnsupportedEncodingException {
        for (final byte b : args[0].getBytes(args[1])) {
            System.out.printf("%1$02X ", (b & 0xFF));
        }
        System.out.println();
    }
}

Test

$ java UseTheForce luke US-ASCII
6C 75 6B 65

$ java UseTheForce luke UTF-8
6C 75 6B 65

$ java UseTheForce luke UTF-16
FE FF 00 6C 00 75 00 6B 00 65

$ java UseTheForce luke UTF-16BE
00 6C 00 75 00 6B 00 65

$ java UseTheForce luke UTF-16LE
6C 00 75 00 6B 00 65 00

$ java UseTheForce luke UTF-32
00 00 00 6C 00 00 00 75 00 00 00 6B 00 00 00 65

May the force be with you.

UPDATE

As describe in Formatter.html#detail, the (b & 0xFF) part is not necessary.

于 2013-09-10T04:32:22.557 回答