Cast string array elements to byte array in java [duplicate] - java

This question already has answers here:
How to convert a String array to a Byte array? (java)
(7 answers)
Closed 7 years ago.
I have a string array of form:
String[] s = {0x22, 0xD2, 0x01}
Now I have to convert it to byte array form like:
byte[] bytes = {(byte)0x22, (byte)0xD2, (byte)0x01}
It can be done in single line in c# but how to do it in Java as I have to append bytes array to another array of same kind and format.
Here I have included some part of the code as I can't include whole code:
String sr = "22D201";
String[] s = {sr.substring(0, 2),sr.substring(2, 4),sr.substring(4)};
byte[] ret = new byte[]{(byte)0x2C, (byte)0x04, (byte)0x01, (byte)0x67, (byte)0x00, (byte)0x00, (byte)0x3D};
Now I have to append byte[] bytes to byte[] ret but I can't as array is in the form of String that is String[] s. So how to covert String[] s so that I can add it to byte[] ret.

You can use String.getBytes();.
You can also initialize a String using a byte array and a specified encoding scheme:
String s = new String(new byte[]{ /* Bytes data. */}, "UTF-8");
For an array of Strings, each individual String's byte array could therefore be processed as follows:
for(final String s : lStrings) {
byte[] lBytes = s.getBytes();
}
If you wanted to make a contiguous array of these types, you could use a ByteArrayOutputStream.
ByteArrayOutputStream b = new ByteArrayOutputStream();
for(final String s : lStrings) {
b.write(s.getBytes());
}
final byte[] lTotalBytes = b.toByteArray();
/* Make sure all the bytes are written. */
b.flush();
/* Close the stream once we're finished. */
b.close();

Related

Why byte array converted to string then convert back to byte array is not same?

First read excel as byte array, then convert this byte array to string, then convert this string to byte array again.
String fileLocation = "/tmp/a.xlsx";
byte[] bytes1 = Files.readAllBytes(Paths.get(fileLocation));
String str = new String(bytes1);
byte[] bytes2 = str.getBytes();
System.out.println(Arrays.equals(bytes1, bytes2)); // false
Why bytes1 is not equals to bytes2?
When you are converting from bytes to a String
String str = new String(bytes1);
you are potentially losing non-char bytes.
As per the javadocs
The behavior of this constructor when the given bytes are not valid in the default charset is unspecified.

Convert InputStream to base64 and then to byte array

I need a byte array, but the requirement is like first I need to convert the input stream to base64 and then the base64 to byte array.
I have tried directly to the byte array, but the requirement is like need to convert the InputStream to base64 and then byte[].
InputStream input = ....
byte[] byteArray = IOUtils.toByteArray(input);
You can use Base64 from java.util package to encode your stream to base 64
Something like this:
String initialString = "original text";
InputStream input = new ByteArrayInputStream(initialString.getBytes());
byte[] byteEncoded = Base64.getEncoder().encode(IOUtils.toByteArray(input));
The method is Base64.getEncoder().encode and have 3 candidates:
public byte[] encode(byte[] src
public int encode(byte[] src,byte[] dst)
public ByteBuffer encode(ByteBuffer buffer)
Hoping that help

Java Conversion from byte[] to char[]

I have wrote a simple snippet in which I try to convert (maybe) a byte array in char array e vice versa.
There are a lot of examples on the Net but this is for me the simplest way to do it.
I need to use array and not strings because its content is a password field to manage.
So I ask you, is this snippet correct?
private static char[] fromByteToCharArrayConverter(byte[] byteArray){
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
clearArray(byteArray);
CharBuffer charBuffer = Charset.forName("UTF-8").decode(buffer);
char[] charArray = new char[charBuffer.remaining()];
charBuffer.get(charArray);
return charArray;
}
private static byte[] fromCharToByteArray(char[] charArray){
CharBuffer charBuffer = CharBuffer.wrap(charArray);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] byteArray = new byte[byteBuffer.remaining()];
byteBuffer.get(byteArray);
return byteArray;
}
Thanks
No, that won't work for (at least) the following reason:
ByteBuffer buffer = ByteBuffer.wrap(byteArray); // Wrap the array
clearArray(byteArray); // Clear the array -> ByteBuffer cleared too

Java: Converting byte string to byte array

I want to convert my byte[] to a String, and then convert that String to a byte[].
So,
byte[] b = myFunction();
String bstring = b.toString();
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser);
bstring gives me [B#74e752bb.
And then convert the String to byte[]. I'm not using it in this order, but this is an example.
How do I need to do this in Java?
When converting byte[] to String, you should use this,
new String(b, "UTF-8");
instead of,
b.toString();
When you are converting byte array to String, you should always specify a character encoding and use the same encoding while converting back to byte array from String. Best is to use UTF-8 encoding as that is quite powerful and compact encoding and can represent over a million characters. If you don't specify a character encoding, then platform's default encoding may be used which may not be able to represent all characters properly when converted from byte array to String.
Your method when dealt appropriately, should be written something like this,
public static void main(String args[]) throws Exception {
byte[] b = myFunction();
// String bstring = b.toString(); // don't do this
String bstring = new String(b, "UTF-8");
byte[] ser = bstring.getBytes("UTF-8");
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser, "UTF-8");
}
I am no expert, but you should try the methods provided by the "Byte" class and if necessary, some loops. Try byte b = Byte.parseByte(String s) to convert a string to a byte and String s = Byte.toString(byte b) to convert a byte to a string. Hope this helps :).
You can do it like this,
String string = "Your String";
byte[] bytesFromString = string.getBytes(); // get bytes from a String
String StringFromByteArray = new String(bytesFromString); // get the String from a byte array

How to convert Java string to byte array? [duplicate]

This question already has answers here:
How to convert Java String into byte[]?
(9 answers)
Closed 6 years ago.
I'm new to Java and I'm sure this is very simple. I've been trying to convert a string to byte[] can't seem to do it. I'm using it for a printer.
ArrayList<byte[]> commands = new ArrayList<byte[]>();
commands.add(new byte[] { 0x1b, 0x2d, 0x00 });
The above works fine but what i need is to be able to take the 0x1b, 0x2d, 0x00 value and insert it from a string like
String hexcode = "0x1b, 0x2d, 0x00";
commands.add(new byte[] { hexcode });
I've tried a ton of stuff can't seem to get it to go.
Try this:
String str = "\u001b\u002d\u0000";
byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1);
This produces a byte array equivalent to new byte[] {0x1b, 0x2d, 0x00}.
Explanation:
A Java String is a sequence of characters
The \uxxxx is how you write a Unicode literal in Java code.
The getBytes(Charset) method does a characters to bytes encoding using the Charset provided.
The Unicode characters \u0000 through \u00ff map straight to 0x00 through 0xff in the ISO_8859_1 (or Latin-1) character set.
Try this. Very simple approach:
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
String hexcode = "0x1b, 0x2d, 0x00";
String[] stringArray = hexcode.split(",");
ArrayList<byte[]> byteArray = new ArrayList<byte[]>();
for (int x = 0; x < stringArray.length; x++) {
byteArray.add(stringArray[x].getBytes());
}
System.out.println(byteArray);
}
}
We just split the first string and create a string array. Then we loop through it generating the bytes for each element pushing those into the ArrayList (which you had in your example).
Spits out:
[B#74a14482, [B#1540e19d, [B#677327b6]

Categories