I am a beginner in java I want to convert String to a byte array and vice versa. when I compare the result input_bytes with output.getBytes(). I found that they are not compatible. this is my code.
String input = "bg#%#bg0";
byte[] input_bytes = input.getBytes();
String output = new String(input_bytes);
System.out.println(input_bytes);
System.out.println(output.getBytes());
the result :
[B#15db9742
[B#6d06d69c
How can I get the same byte array from input and output? and what is the problem in my code?
Try:
System.out.println(Arrays.toString(input_bytes));
You need to use Arrays.toString() method.
Output: [98, 103, 64, 37, 64, 98, 103, 48]
Note: Here Arrays.toString(byte[]) returns a string representation of the contents of the specified byte array.
Related
I'm trying to convert byte array which holds hex values.
byte[] bytes = {48, 48, 48, 48, 48, 51, 51, 99}
for example : 48, 48, 48, 48, 48, 51, 51, 99 is 0000033c and converted to int is 828.
The only way to convert is converting it to String and then parse integer from String.
public static int ConvertValueFromBytes(byte[] bytes)
{
String b = new String(bytes);
return Converter.ConvertHexToInt(b);
}
The main problem here is performance, calling it many times can cause performance issues. When trying parse int value from byte array I get massive numbers, thats why I'm parsing from String, to get the correct value.
Is there a better way or solution to this ?
Whilst it's very unclear why you would represent the data in this way, it's easy to transform without using a string:
int v = 0;
for (byte b : bytes) {
v = 16 * v + Character.getNumericValue(b);
}
Ideone demo
I have a byte array,
[102, 100, 51, 52, 48, 48]
Which has the hex string representation:
"fd3400"
Which if I convert it to a number, shows as being 16593920.
However, when I convert it using the snippet below
int iSec = ByteBuffer.wrap(bSec).order(ByteOrder.LITTLE_ENDIAN).getInt();
I get the result: 875783270. The bytes are supposed to be in LSB format, but I can't seem to get the correct value out, as 875783270 != 16593920. I'm getting kind of confused with these data formats.
Byte array contains the byte representation of a string.
In ASCII:
102 == 'f'
100 == 'd'
51 == '3'
52 == '4'
48 == '0'
You should convert from byte array to string and then parse that string using base 16 (hexadecimal).
String hex = new String(arr, "ASCII"); //fd3400
int number = Integer.valueOf(hex, 16).intValue(); //16593920
I need to save a variable on a JavaCard. Javacard's don't support Strings, so I have to hardcode some String variables as byte arrays.
Unfortunately, I don't know how to achieve this format:
new byte[]{0x4A, 0x61, 0x6E, 0x20, 0x56, 0x6F, 0x73, 0x73, 0x61, 0x65, 0x72, 0x74};
Is there an online tool available? Or is there a program that output's it that way so I can copy paste the output and use that for hardcoding?
You don't need any tool for that. If you want to store an string in your applet in the applet developing step (I mean in the programming phase) use a byte array as below :
public static byte[] myFiled = {(byte)'T', (byte)'E', (byte)'S', (byte)'T'};
or use Hex values instead of the letters:
public static byte[] myFiled = {(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13};
It's necessary to cast the array elements to byte explicitly
And if you want to store the string after developing in installing your applet, first convert it to its hex value using this online tool for example, and then send it to card in the data field of an APDU command. And then using arrayCopy or arrayCopyNonAtomic methods store it in you byte array.
Just use String::getBytes():
String a = "HelloWorld";
byte[] inBytes = a.getBytes();
System.out.println(Arrays.toString(inBytes));
OUTPUT:
[72, 101, 108, 108, 111, 87, 111, 114, 108, 100]
IDEONE DEMO
ADD ON: as #AndyTurner mentioned, you can specify charset using String::getBytes(Charset).
Find here a nice explanation.
Here's a method to convert a string to an array literal that represents US-ASCII–encoded bytes.
static String format(String str)
{
byte[] encoded = str.getBytes(StandardCharsets.US_ASCII);
return IntStream.range(0, encoded.length)
.mapToObj(idx -> String.format("0x%02X", encoded[idx]))
.collect(Collectors.joining(", ", "{ ", " }"));
}
Because it uses ASCII, the high bit of each byte is zero, and no downcasts to byte are required.
I have to convert an existing Java code for encryption to PHP.
I am stuck in the below Java code where the key is converted to a byte array using Java's BigInteger class
private static byte[] stringToBytes(String str){
byte[] bytes=new BigInteger(str, Character.MAX_RADIX).toByteArray();
return Arrays.copyOfRange(bytes, 1, bytes.length);
}
I am able to convert the input string to big int using
base_convert($key,36,10);
But cannot convert to byte array.
Any inputs please
A sample output for Java code is shown below
stringToBytes("TestString")
gives
[10, -100, -89, -107, 122, -108, 44]
I have a file I need to search for encoded tags, and retrieve data identified by them. Tags are 4 Bytes long and identify either ascii strings of variable length or two-byte-integer values encoded Little-Endian.
The tags appear to all be on 4 byte boundaries and all within the first 2000 bytes of the start of the file. I have tried various ways of searching the file. The only one that has worked has been a byte by byte compare using decimal integer values.
One solution found on SO but not exactly for this problem suggested: indexOfSubList().
I tried this test but the result is -1.
byte[] needle = {68,73,67,77};
byte[] hayStack = {00, 01, 68,73,67,77, 11, 45};
location = Collections.indexOfSubList(Arrays.asList(hayStack), Arrays.asList(needle));
I am by no means wedded to this code and would appreciate any other thoughts or solutions.
Your question is kind of vague, do you mean something like this:
// simplified way of identifying tag by first byte of it,
// make it more complex as needed
byte startOfTag = 65;
// for loop assumes tags start at even 4 byte boundary, if not, modify loop
for(int i = 0; i <= data.length-4 ; i += 4) {
if (data[i] == startOfTag) {
myTagHandlerMethod(data[i], data[i+1], data[i+2], data[i+3]);
}
}
You get -1 from Collections.indexOfSubList, because Arrays.asList does not work as you expect for byte[]: it returns List<byte[]>, not List<Byte>. Containers must contain object references, unboxed numeric types not allowed... This should work:
Byte[] needle = {68,73,67,77};
Byte[] hayStack = {00, 01, 68,73,67,77, 11, 45};
location = Collections.indexOfSubList(Arrays.asList(hayStack), Arrays.asList(needle));
If you want to avoid re-inventing wheel while manipulating primitive type arrays, you can use Google's Guava libs. It has for example an indexOf method which you could use here.
By converting your byte arrays to Byte arrays, you will get the result you desire:
Byte[] needle = { 68, 73, 67, 77 };
Byte[] hayStack = { 00, 01, 68, 73, 67, 77, 11, 45 };
location = Collections.indexOfSubList(Arrays.asList(hayStack),
Arrays.asList(needle));
// location now equals 2
This is because Arrays.asList doesn't operate as you'd imagine on byte[] objects. It returns a List<byte[]> rather than a List<Byte>.