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.
Don't try to treat Unicode characters as bytes! 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.
Related
I have an enum
public enum Test {
VALUE, NAME;
}
I convert it into a byte array
byte[] array = Test.VALUE.toString().getBytes(Charsets.UTF_8)
how can i convert that back into an enum?
Test.valueOf(array.toString()) does not work.
The reason why array.toString didn't work is that toString returns a description of the array, not the string constructed using the bytes in the array with UTF-8 encoding. toString just returns something like [B#60e53b93 which means practically nothing to humans.
To convert a byte array to a string, use the string's constructor, the one that takes a byte array and a Charset. Here's the whole code:
// converting to byte array
Test t = Test.VALUE;
byte[] bytes = t.toString().getBytes(StandardCharsets.UTF_8);
// converting back to Test
String str = new String(bytes, StandardCharsets.UTF_8);
Test newT = Test.valueOf(str);
If you think about it logically, toString can't possibly give you what you expect. This is because to convert a byte array to a string, you need to specify an encoding! You obvious did not pass a Charset object when you call toString, so how on earth is the computer going to know what charset you want?
You have to convert the array back to a proper String first using it constructor. array.toString() does not do what you think and will only return gibberish.
byte[] array = Test.VALUE.toString().getBytes(Charsets.UTF_8);
String valueString = new String(array, Charsets.UTF_8);
Test value = Test.valueOf(valueString);
Here below is how I generate a SecureRandom:
byte[] arr = SecureRandom.getInstance("SHA1PRNG").generateSeed(32);
then, I convert it to a string like this:
String str = new String(arr)
and finally, I try to convert the string back to my original byte array:
byte[] arr2 = str.getBytes()
The problem is that the last statement does not return my original byte array... Am I missing something?
then, I convert it to a string like this:
Don't do that!
You have two problems here:
this constructor will use the default encoding;
even if you used UTF-8 as an encoding, some byte sequences just cannot be encoded to chars!
You should not use String to hold binary data; or use a string-based encoding, such as Base64.
For more information, see CharsetDecoder and CodingErrorAction.
Is it possible to convert a byte array to a string but where the length of the string is exactly the same length as the number of bytes in the array? If I use the following:
byte[] data; // Fill it with data
data.toString();
The length of the string is different than the length of the array. I believe that this is because Java and/or Android takes some kind of default encoding into account. The values in the array can be negative as well. Theoretically it should be possible to convert any byte to some character. I guess I need to figure out how to specify an encoding that generates a fixed single byte width for each character.
EDIT:
I tried the following but it didn't work:
byte[] textArray; // Fill this with some text.
String textString = new String(textArray, "ASCII");
textArray = textString.getBytes("ASCII"); // textArray ends up with different data.
You can use the String constructor String(byte[] data) to create a string from the byte array. If you want to specify the charset as well, you can use String(byte[] data, Charset charset) constructor.
Try your code sample with US-ASCII or ISO-8859-1 in place of ASCII. ASCII is not a built-in Character encoding for Java or Android, but one of those two are. They are guaranteed single-byte encodings, with a caveat that characters not in the character set will be silently truncated.
This should work fine!
public static byte[] stringToByteArray(String pStringValue){
int length= pStringValue.length();
byte[] bytes = new byte[length];
for(int index=0; index<length; index++){
char ch= pStringValue.charAt(index);
bytes[index]= (byte)ch;
}
return bytes;
}
since JDK 1.6:
You can also use:
stringValue.getBytes() which will return you a byte array.
In case of passing a NULL string, you need to handle that by either throwing the nullPointerException or handling it inside the method itself.
This is simply to error check my code, but I would like to convert a single byte out of a byte array to a string. Does anyone know how to do this? This is what I have so far:
recBuf = read( 5 );
Log.i( TAG, (String)recBuf[0] );
But of course this doesn't work.
I have googled around a bit but have only found ways to convert an entire byte[] array to a string...
new String( recBuf );
I know I could just do that, and then sift through the string, but it would make my task easier if I knew how to operate this way.
You can make a new byte array with a single byte:
new String(new byte[] { recBuf[0] })
Use toString method of Byte
String s=Byte.toString(recBuf[0] );
Try above , it works.
Example:
byte b=14;
String s=Byte.toString(b );
System.out.println("String value="+ s);
Output:
String value=14
There's a String constructor of the form String(byte[] bytes, int offset, int length). You can always use that for your conversion.
So, for example:
byte[] bite = new byte[]{65,67,68};
for(int index = 0; index < bite.length; index++)
System.out.println(new String(bite, index,1));
What about converting it to char? or simply
new String(buffer[0])
public static String toString (byte value)
Since: API Level 1
Returns a string containing a concise, human-readable description of the specified byte value.
Parameters
value the byte to convert to a string.
Returns
a printable representation of value.]1
this is how you can convert single byte to string try code as per your requirement
Edit:
Hows about
""+ recBuf[0];//Hacky... not sure if would work
((Byte)recBuf[0]).toString();
Pretty sure that would work.
Another alternate could be converting byte to char and finally string
Log.i(TAG, Character.toString((char) recBuf[0]));
Or
Log.i(TAG, String.valueOf((char) recBuf[0]));
You're assuming that you're using 8bit character encoding (like ASCII) and this would be wrong for many others.
But with your assumption you might just as well using simple cast to character like
char yourChar = (char) yourByte;
or if really need String:
String string = String.valueOf((char)yourByte);
I am reading a char array from a file in and then converting it too a string using the String constructor.
read = fromSystem.read(b);
String s = new String(b);
This code has been in the program for ages and works fine, although until now it has been reading the full size of the array, 255 chars, each time. Now I am reusing the class for another purpose and the size of what it reads varies. I am having the problem that if it reads, say 20 chars, then 15, the last 5 of the previous read are still in the byte array. To overcome this I added a null char at the end of what had been read.
read = fromSystem.read(b);
if (read < bufferLength) {
b[read] = '\0';
}
String s = new String(b);
If I then did
System.out.println(b);
It works, the end of the buffer doens't show. However, if I pass that string into a message dialog then it still shows. Is there some other way that I should terminate the string?
Use:
String s = new String(b, 0, read)
instead.
You need to use the String constructor that allows you to specify the range of bytes that are valid in the byte array.
String(byte[] bytes, int offset, int length);
Using it like this:
read = fromSystem.read(b);
String s = new String(b, 0, read);