简体   繁体   English

Java byte []数组中项目的相反顺序

[英]reverse order of items in a Java byte[] array

i have a problem reversing the order of items in a bytearray correctly. 我在正确反转字节数组中的项目顺序时遇到问题。 I want to flip the following String to the one below: 我想将下面的字符串翻转到下面的字符串:

original "\Я\Ґ\И\в\е\т" 原始的“ \\ u042F \\ u0490 \\ u0418 \\ u0432 \\ u0435 \\ u0442”

flipped "\т\е\в\И\Ґ\Я" 翻转“ \\ u0442 \\ u0435 \\ u0432 \\ u0418 \\ u0490 \\ u042F”

I tried someonething like this, but this doesn't work. 我尝试过这样的事情,但这不起作用。

public byte[] invert(byte[] input) {
    ByteBuffer bb = ByteBuffer.wrap(input);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    byte[] b = bb.array();
    return b;
}

any ideas? 有任何想法吗?

This will do what your example shows you're looking for: 这将完成您的示例显示的内容:

String reversed = new StringBuilder(str).reverse().toString();

You may need to decode a byte[] to a String , and then encode the reversed String back to a byte[] using the correct character encoding. 您可能需要将byte[]解码为String ,然后使用正确的字符编码将反向的String编码回byte[]

Don't try to treat Unicode characters as bytes! 不要尝试将Unicode字符视为字节! The simplest way to do this is create a String ( String(byte[]) ) get the characters ( String.toCharArray() ) and write them into a char[] in reverse order, then go back to a byte array via a String again. 最简单的方法是创建一个String( String(byte[]) )获取字符( String.toCharArray() )并将它们以相反的顺序写入char[] ,然后通过String返回一个字节数组再次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM