I have a String value as "0x0601930600058000050001", need to convert to byte array
byte[] codes1 = new byte[]{(byte)0x06,(byte)0x01,(byte)0x93,(byte)0x06,(byte)0x00,(byte)0x05,(byte)0x80,(byte)0x00,(byte)0x05,(byte)0x00,(byte)0x01};
for(byte b : codes1){
System.out.println(b);
}
System.out.println("======================");
byte[] cod = "0x0601930600058000050001".getBytes();
for(byte b : cod){
System.out.println(b);
}
Both the results are different, how to make them same. 1st loop output is the actual one what i am expecting, 2nd loop is wrong output.
If you see, i am splitting each 2 bytes and type casting and using 0x to get the actual value.
Question : Is there any predefined method (Apache commons codec) which can help me to do the same task as 1st loop ? I get that String value dynamically at run time.
Please suggest.
Thanks!
Your string is a hexadecimal representation of a byte array!
With guava you can do this:
byte[] bytes = BaseEncoding.base16().decode(mystring)
I would go for:
byte[] result = myString.getBytes();
or
byte[] result = myString.getBytes(Charset.forName("UTF-8"));
Related
Say we have a byte[] array:
byte[] data = {10,10,1,1,9,8}
and I want to convert these values in to a hexadecimal string:
String arrayToHex = "AA1198"
How can I do this? Using Java language in IntelliJ. Keep in mind this is my first semester of coding, so I'm already feeling lost.
First I start with this method:
public static String toHexString(byte[] data)
In the problem I'm trying to solve, we get a string from a user input, which is then converted to a byte[] array, and from there must be converted back into a string in hexadecimal format. But for simplification purposes I am just trying to input my own array.
So, here I have my array:
byte[] data = {10,10,1,1,9,8}
I know how to just print the byte array by just saying:
for (int i = 0; i < data.length; i++)
{
System.out.print(data[i]);
}
which will have an output of:
10101198
but obviously this is not what I'm looking for, as I have to convert the 10s to As, and I need a String type, not just an output. I'm sorry I'm so vague, but I'm truly lost and ready to give up!
This is not what you would normally do and would only work for byte values from 0 to 15.
byte[] data = {10,10,1,1,9,8};
StringBuilder sb = new StringBuilder();
for (byte b : data)
sb.append(Integer.toHexString(b));
String arrayAsHex = sb.toString();
What you would normally expect is "0A0A01010908" so that any byte value is possible.
String arrayAsHex = DatatypeConverter.printHexBinary(data);
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.
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 have a byte array in java. That array contains '%' symbol somewhere in it. I want to find the position of that symbol in that array. Is there any way to find this?
Thanks in Advance!
[EDIT]
I tried below code and it worked fine.
byte[] b = {55,37,66};
String s = new String(b);
System.out.println(s.indexOf("%"));
I have a doubt. Is every character takes exactly one byte in java?
A correct and more direct Guava solution:
Bytes.indexOf(byteArray, (byte) '%');
using Google Guava:
com.google.common.primitives.Bytes.asList(byteArray).indexOf(Byte.valueOf('%'))
I come from the future with some streaming and lambda stuff.
If it's just a matter of finding a byte in a byte[]:
Input:
byte[] bytes = {55,37,66};
byte findByte = '%';
With streaming and lambda stuff:
OptionalInt firstMatch = IntStream.range(0, bytes.length).filter(i -> bytes[i] == findByte).findFirst();
int index = firstMatch.isPresent ? firstMatch.getAsInt() : -1;
Which is pretty much the same as:
Actually, I think I still just prefer this. (e.g. and put it in some utility class).
int index = -1;
for (int i = 0 ; i < bytes.length ; i++)
if (bytes[i] == findByte)
{
index = i;
break;
}
EDIT
Your question is actually more about finding a character rather than finding a byte.
What could be improved in your solution:
String s = new String(bytes); // will not always give the same result
// there is an invisible 2nd argument : i.e. charset
String s = new String(bytes, charset); // default charset depends on your system.
So, your program may act different on different platforms.
Some charsets use 1 byte per character, others use 2, 3, ... or are irregular.
So, the size of your string may vary from platform to platform.
Secondly, some byte sequences cannot be represented as strings at all. i.e. if the charset does not have a character for the matching value.
So, how could you improve it:
If you just know that your byte array will always contain plain old ascii values, you could use this:
byte[] b = {55,37,66};
String s = new String(b, StandardCharsets.US_ASCII);
System.out.println(s.indexOf("%"));
On the other hand, if you know that your content contains UTF-8 characters, use :
byte[] b = {55,37,66};
String s = new String(b, StandardCharsets.UTF-8);
System.out.println(s.indexOf("%"));
etc ...
Basically, I'm looking for .NET's BitConverter.
I need to get bytes from String, then parse them to long value and store it. After that, read long value, parse to byte array and create original String. How can I achieve this in Java?
Edit: Someone did already ask similar question. I am looking more like for samples then javadoc reference ...
String has a getBytes method. You could use this to get a byte array.
To store the byte-array as longs, I suggest you wrap the byte-array in a ByteBuffer and use the asLongBuffer method.
To get the String back from an array of bytes, you could use the String(byte[] bytes) constructor.
String input = "hello long world";
byte[] bytes = input.getBytes();
LongBuffer tmpBuf = ByteBuffer.wrap(bytes).asLongBuffer();
long[] lArr = new long[tmpBuf.remaining()];
for (int i = 0; i < lArr.length; i++)
lArr[i] = tmpBuf.get();
System.out.println(input);
System.out.println(Arrays.toString(lArr));
// store longs...
// ...load longs
long[] longs = { 7522537965568945263L, 7955362964116237412L };
byte[] inputBytes = new byte[longs.length * 8];
ByteBuffer bbuf = ByteBuffer.wrap(inputBytes);
for (long l : longs)
bbuf.putLong(l);
System.out.println(new String(inputBytes));
Note that you probably want to store an extra integer telling how many bytes the long-array actually stores, since the number of bytes may not be a multiple of 8.