byte[] toString() gives a weird string instead of actual value - java

byte[] a has value of {119}, which is the ascii equivalent of "w", but when I use .toString() to convert it to string, it gives me a weird string. any idea what I did wrong?
byte[] a = characteristicRX.getValue();
String rscvString = a.toString();
Log.d("byteToHex", "rscvString = " + rscvString);
while ( rscvString != "w" ){

String object takes a parameter of byte[] as an overloaded constructor. Use String rscvString = new String(a); and you should be sorted
You can't use boolean operators to test against strings ie. != or ==.
use while ( !(rscvString.equalsIgnoreCase("w") ) the equalsIgnoreCase() method will return a boolean and the ! will force the test against the false.

Try one of the lines below to cast a byte to a character and transform it to String
String rscvString = String.valueOf((char) a);
String rscvString = String.valueOf((char) (a & 0xFF));
You can pass a byte array in the String constructor to get a String object of your array.

Related

Whats wrong with the following code

Why isn't the following code working ?
String s = "fecbda";
Arrays.sort(s.toCharArray());
System.out.println(s);
Strings are immutable so you can't change them, and you shouldn't expect this to do anything.
What you might have intended is
String s = "fecbda";
char[] chars = s.toCharArray();
Arrays.sort(chars);
String s2 = new String(chars);
System.out.println(s2);
It does not work as s.toCharArray():
Returns:
a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
The operative part of the documentation is that it creates a new array (i.e. a copy of the characters in the string) and when you sort that array you do not sort the String.
You cannot sort the string as it is immutable but you can make a new string out of the sorted character array like this:
String s = "fecbda";
char[] c = s.toCharArray();
Array.sort( c );
String n = new String( c );
As an alternative method, you can do it in Java 8 using streams:
String s = "fecbda";
String n = s.chars() // Convert to an IntStream of character codes
.sorted() // Sort
.mapToObj(i -> Character.toString((char) i)) // Convert to strings
.collect(Collectors.joining()); // Concatenate the strings.

Covert UTF-16 Character Code (number) to String in Java

How do I simply convert a UTF-16 character to String?
something Like
String str = TheMagicalFunction(0x25E6);
You can use Character.toString(char):
String str = Character.toString((char) 0x25E6);
You can omit the cast when first storing the character in a variable …
char whiteBullet = 0x25E6;
String whiteBulletString = Character.toString(whiteBullet);
… or when using a Unicode escape which in this case is easy since the character belongs to the Basic Multilingual Plane (BMP):
String str = Character.toString('\u25E6');
The method String.valueOf(char) is equivalent and/but has multiple overloads. Beware of this:
String str = String.valueOf(0x25E6); // "9702" (decimal value)
String str2 = String.valueOf((char) 0x25E6); // "◦"
String str3 = String.valueOf('\u25E6'); // "◦"
You need to:
If the character is an integer, cast it to char.
Put it in a 1-element char[].
Pass it the the String constructor.
So,
String str = new String(new char[] {(char) 0x25E6});

Concat the two first characters of string

I have a String s = "abcd" and I want to make a separate String c that is let's say the two first characters of String s. I use:
String s = "abcd";
int i = 0;
String c = s.charAt(i) + s.charAt(i+1);
System.out.println("New string is: " + c);
But that gives error: incompatible types. What should I do?
You should concatenate two Strings and not chars. See String#charAt, it returns a char. So your code is equivalent to:
String c = 97 + 98; //ASCII values for 'a' and 'b'
Why? See the JLS - 5.6.2. Binary Numeric Promotion.
You should do:
String c = String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1));
After you've understood your problem, a better solution would be:
String c = s.substring(0,2)
More reading:
ASCII table
Worth knowing - StringBuilder
String#substring
What you should do is
String c = s.substring(0, 2);
Now why doesn't your code work? Because you're adding two char values, and integer addition is used to do that. The result is thus an integer, which can't be assigned to a String variable.
String s = "abcd";
First two characters of the String s
String firstTwoCharacter = s.substring(0, 2);
or
char c[] = s.toCharArray();
//Note that this method simply returns a call to String.valueOf(char)
String firstTwoCharacter = Character.toString(c[0])+Character.toString(c[1]);
or
String firstTwoCharacter = String.valueOf(c[0])+ String.valueOf(c[1]);

Transform String value to bytearray java

I have a string which contains the byte array's String value for example like this [B#42031498
I want to retrieve the String content as byte[] ? How can I do that ?
PS : converting the string with String.getBytes() method doesn't work . It converts the string but doesn't give me the value as byte array. It works like this.
If It's is not possible is there a way to get byte[] from Object in java (and always without converting)
converting the string with String.getBytes() method doesn't work . It converts the string but doesn't give me the value as byte array.
Yes it does.
You have two problems:
you try and print the array directly; you should use Arrays.toString(), otherwise the .toString() method of the array itself is called;
you don't specify the encoding; you should really use .getBytes(StandardCharsets.UTF_8) to have the same result on all environments.
In the same manner, building a string from a byte array should be done using the correct encoding: new String(array, StandardCharsets.UTF_8).
if [B#42031498 has already been saved into a String, there is no way you can get this back to the originating byte array. Look at the following example:
String str = "[B#42031498";
byte[] ba = str.getBytes();
String s = new String(ba);
System.out.println(s);
This will output [B#42031498
What you have done:
byte[] array = ....
String result = array.toString();
What you (probably) want:
String result = new String(array, "UTF-8");
Iterate the byte array as below and you will get the byte value :
for (byte b : bytes) {
System.out.println(b);
}
The output B#42031498 you get because of Object class toString() method .
public String toString()
{
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}

How to convert hex strings to byte values in Java

I have a String array.
I want to convert it to byte array.
I use the Java program.
For example:
String str[] = {"aa", "55"};
convert to:
byte new[] = {(byte)0xaa, (byte)0x55};
What can I do?
String str = "Your string";
byte[] array = str.getBytes();
Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?
If yes, then for each string item I would do the following:
check that a string consists only of 2 characters
these chars are in '0'..'9' or 'a'..'f' interval (take their case into account
as well)
convert each character to a corresponding number, subtracting code value of '0' or 'a'
build a byte value, where first char is higher bits and second char is lower ones. E.g.
int byteVal = (firstCharNumber << 4) | secondCharNumber;
Convert string to Byte-Array:
byte[] theByteArray = stringToConvert.getBytes();
Convert String to Byte:
String str = "aa";
byte b = Byte.valueOf(str);
You can try something similar to this :
String s = "65";
byte value = Byte.valueOf(s);
Use the Byte.ValueOf() method for all the elements in the String array to convert them into Byte values.
A long way to go :). I am not aware of methods to get rid of long for statements
ArrayList<Byte> bList = new ArrayList<Byte>();
for(String ss : str) {
byte[] bArr = ss.getBytes();
for(Byte b : bArr) {
bList.add(b);
}
}
//if you still need an array
byte[] bArr = new byte[bList.size()];
for(int i=0; i<bList.size(); i++) {
bArr[i] = bList.get(i);
}
Since there was no answer for hex string to single byte conversion, here is mine:
private static byte hexStringToByte(String data) {
return (byte) ((Character.digit(data.charAt(0), 16) << 4)
| Character.digit(data.charAt(1), 16));
}
Sample usage:
hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16
Or you can also try the Integer.parseInt(String number, int radix) imo, is way better than others.
// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201
String source = "testString";
byte[] byteArray = source.getBytes(encoding);
You can foreach and do the same with all the strings in the array.
The simplest way (using Apache Common Codec):
byte[] bytes = Hex.decodeHex(str.toCharArray());
String str[] = {"aa", "55"};
byte b[] = new byte[str.length];
for (int i = 0; i < str.length; i++) {
b[i] = (byte) Integer.parseInt(str[i], 16);
}
Integer.parseInt(string, radix) converts a string into an integer, the radix paramter specifies the numeral system.
Use a radix of 16 if the string represents a hexadecimal number.
Use a radix of 2 if the string represents a binary number.
Use a radix of 10 (or omit the radix paramter) if the string represents a decimal number.
For further details check the Java docs: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)
Here, if you are converting string into byte[].There is a utility code :
String[] str = result.replaceAll("\\[", "").replaceAll("\\]","").split(", ");
byte[] dataCopy = new byte[str.length] ;
int i=0;
for(String s:str ) {
dataCopy[i]=Byte.valueOf(s);
i++;
}
return dataCopy;

Categories

Resources