How to print the data in byte array as characters? - java

In my byte array I have the hash values of a message which consists of some negative values and also positive values. Positive values are being printed easily by using the (char)byte[i] statement.
Now how can I get the negative value?

How about Arrays.toString(byteArray)?
Here's some compilable code:
byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));
Output:
[-1, -128, 1, 127]
Why re-invent the wheel...

If you want to print the bytes as chars you can use the String constructor.
byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));

Try it:
public static String print(byte[] bytes) {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (byte b : bytes) {
sb.append(String.format("0x%02X ", b));
}
sb.append("]");
return sb.toString();
}
Example:
public static void main(String []args){
byte[] bytes = new byte[] {
(byte) 0x01, (byte) 0xFF, (byte) 0x2E, (byte) 0x6E, (byte) 0x30
};
System.out.println("bytes = " + print(bytes));
}
Output: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]

Well if you're happy printing it in decimal, you could just make it positive by masking:
int positive = bytes[i] & 0xff;
If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.

Try this one : new String(byte[])

byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
System.out.format("%d ", c);
}
System.out.println();
gets you
1 -2 5 66

in Kotlin you can use :
println(byteArray.contentToString())

Related

byte values in hex format and writes these to the byte stream?

Takes a sequence of byte values in hex format and writes these to the byte stream.
"01 02 1a" => writes bytes 0x01 0x02 0x1a to the byte stream.
What does this mean?
Here is a possible solution:
String hex = "01 02 1a";
// Remove spaces
hex = hex.replace(" ", "");
// Array containing bytes
byte[] bytes = new byte[hex.length() / 2];
int k = 0;
for(int i=0; i < hex.length(); i = i +2 ) {
// Read and parse each byte
int b = Integer.parseInt(hex.substring(i, i + 2), 16);
bytes[k] = (byte) b;
k++;
}
// Write bytes to an outputStram
OutputStream out;
for(Byte b: bytes) {
out.write(b);
}

Convert Integer to Hex String

i have an Integer value and i want to convert it on Hex.
i do this:
private short getCouleur(Integer couleur, HSSFWorkbook classeur) {
if (null == couleur) {
return WHITE.index;
} else {
HSSFPalette palette = classeur.getCustomPalette();
String hexa = Integer.toHexString(couleur);
byte r = Integer.valueOf(hexa.substring(0, 2), 16).byteValue();
byte g = Integer.valueOf(hexa.substring(2, 4), 16).byteValue();
byte b = Integer.valueOf(hexa.substring(4, 6), 16).byteValue();
palette.setColorAtIndex((short) 65, r, g, b);
return (short) 65;
}
}
In output i have this:
couleur: 65331
Hexa: FF33
hexa.substring(0, 2): FF
hexa.substring(2, 4): 33
hexa.substring(4, 6):
r: -1
g: 51
b: error message
error message: String index out of range: 6
Thx.
you can call the method in JDK.
String result = Integer.toHexString(131);
If I understand correctly you want to split an int into three bytes (R, G, B).
If so, then you can do this by simply shifting the bits in the integer:
byte r = (byte)((couleur >> 16) & 0x000000ff);
byte g = (byte)((couleur >> 8) & 0x000000ff);
byte b = (byte)(couleur & 0x000000ff);
That's much more efficient. You don't have to do it through conversion to String.
The problem is that you are assuming that the hex string will be six digits long.
try String.format ("%06d", Integer.toHexString(couleur));
to pad it with zeros if less than 6 digits longs

Switching hexadecimal symbols in a byte

I want to switch the two hexadecimals symbols in a byte, for example if
input = 0xEA
then
output = 0xAE
It has to be in java.
I already have this method I made, but it only works in some cases:
public static final byte convert(byte in){
byte hex1 = (byte) (in << 4);
byte hex2 = (byte) (in >>> 4);
return (byte) (hex1 | hex2);
}
A working example is:
input: 0x3A
hex1: 0xA0
hex2: 0x03
output: 0xA3
A not working example is:
input: 0xEA
hex1: 0xA0
hex2: 0xFE
output: 0xFE
Anyone can shed some lights on why this is not working?
I suspect the problem is the sign extension. Specifically, you probably need to do
byte hex2 = (byte) ((in >>> 4) & 0xF);
try
byte hex1 = (byte) (in << 4);
byte hex2 = (byte) ( in >>> 4);
return (byte) (hex1 | hex2 & 0x0F);
this is like in a known puzzle
byte x = (byte)0xFF;
x = (byte) (x >>> 1);
System.out.println(x);
prints -1 because before unsigned shift 0xFF is promoted to int -> 0xFFFFFFFF; after shift it is 0x7FFFFFFF; cast to byte -> 0xFF
but
byte x = (byte)0xFF;
x = (byte) ((x & 0xFF) >>> 1);
System.out.println(x);
prints 127 because we truncated 0xFFFFFFFF -> 0x000000FF, now shift produces 0x0000007F, cast to byte -> 0x7F
Actually, this promotion is done at compile time. JVM works only with 4 or 8 bytes operands (local variables on stack). Even boolean in bytecode is 0 or 1 int.

Java Programming: Integer value to Hexadecimal

I have an integer and I want to convert it to hex value. I am building a message header with each byte value of this array below indicating a specific information about the message.
I want to represent the length of the message in 2 bytes len1 and len2 below.
How do I do this?
byte[] headerMsg =new byte [] { 0x0A, 0x01, 0x00, 0x16,
0x11, 0x0d, 0x0e len1 len2};
int lenMsg //in 2 bytes
Thanks
byte[] headerMsg =new byte [] {
0x0A, 0x01, 0x00, 0x16,
0x11, 0x0d, 0x0e,
0x00, 0x00 // to be filled with length bytes
};
int hlen = headerMsg.length;
// I assume the bodyMsg byte array is defined elsewhere
int lenMsg = hlen + bodyMsg.length;
// lobyte of length - mask just one byte with 0xFF
headerMsg[hlen - 1] = (byte) (lenMsg & 0xFF);
// hibyte of length - shift to the right by one byte and then mask
headerMsg[hlen - 2] = (byte) ((lenMsg >> 8) & 0xFF);

How to convert a byte array to its numeric value (Java)?

I have an 8 byte array and I want to convert it to its corresponding numeric value.
e.g.
byte[] by = new byte[8]; // the byte array is stored in 'by'
// CONVERSION OPERATION
// return the numeric value
I want a method that will perform the above conversion operation.
One could use the Buffers that are provided as part of the java.nio package to perform the conversion.
Here, the source byte[] array has a of length 8, which is the size that corresponds with a long value.
First, the byte[] array is wrapped in a ByteBuffer, and then the ByteBuffer.getLong method is called to obtain the long value:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();
System.out.println(l);
Result
4
I'd like to thank dfa for pointing out the ByteBuffer.getLong method in the comments.
Although it may not be applicable in this situation, the beauty of the Buffers come with looking at an array with multiple values.
For example, if we had a 8 byte array, and we wanted to view it as two int values, we could wrap the byte[] array in an ByteBuffer, which is viewed as a IntBuffer and obtain the values by IntBuffer.get:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);
System.out.println(i0);
System.out.println(i1);
Result:
1
4
Assuming the first byte is the least significant byte:
long value = 0;
for (int i = 0; i < by.length; i++)
{
value += ((long) by[i] & 0xffL) << (8 * i);
}
Is the first byte the most significant, then it is a little bit different:
long value = 0;
for (int i = 0; i < by.length; i++)
{
value = (value << 8) + (by[i] & 0xff);
}
Replace long with BigInteger, if you have more than 8 bytes.
Thanks to Aaron Digulla for the correction of my errors.
If this is an 8-bytes numeric value, you can try:
BigInteger n = new BigInteger(byteArray);
If this is an UTF-8 character buffer, then you can try:
BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));
Simply, you could use or refer to guava lib provided by google, which offers utiliy methods for conversion between long and byte array. My client code:
long content = 212000607777l;
byte[] numberByte = Longs.toByteArray(content);
logger.info(Longs.fromByteArray(numberByte));
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
Complete java converter code for all primitive types to/from arrays
http://www.daniweb.com/code/snippet216874.html
Each cell in the array is treated as unsigned int:
private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
return res;
for (int i=0;i<bytes.length;i++){
res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}
public static long byteArrayToLong(byte[] bytes) {
return ((long) (bytes[0]) << 56)
+ (((long) bytes[1] & 0xFF) << 48)
+ ((long) (bytes[2] & 0xFF) << 40)
+ ((long) (bytes[3] & 0xFF) << 32)
+ ((long) (bytes[4] & 0xFF) << 24)
+ ((bytes[5] & 0xFF) << 16)
+ ((bytes[6] & 0xFF) << 8)
+ (bytes[7] & 0xFF);
}
convert bytes array (long is 8 bytes) to long
You can try use the code from this answer: https://stackoverflow.com/a/68393576/7918717
It parses bytes as a signed number of arbitrary length. A few examples:
bytesToSignedNumber(false, 0xF1, 0x01, 0x04) returns 15794436 (3 bytes as int)
bytesToSignedNumber(false, 0xF1, 0x01, 0x01, 0x04) returns -251592444 (4 bytes as int)
bytesToSignedNumber(false, 0xF1, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04) returns -1080581331768770303 (8 of 9 bytes as long)

Categories