byte[] to int and viceversa java [duplicate] - java

This question already has answers here:
Byte Array and Int conversion in Java
(10 answers)
Closed 8 years ago.
I have a method that converts int to byte[]
private static byte[] intToBytes(int i)
{
byte[] integerBs = new byte[MAX_INT_LEN];
integerBs[0] = (byte) ((i >>> 24) & 0xFF);
integerBs[1] = (byte) ((i >>> 16) & 0xFF);
integerBs[2] = (byte) ((i >>> 8) & 0xFF);
integerBs[3] = (byte) (i & 0xFF);
return integerBs;
}
Let's say I try to convert the integer 4 to bits:
byte[] lenBs = intToBytes(4);
int a=(int)lenBs[0];
System.out.println("result:"+a);
The value of MAX_INT_LENGTH is 4
I get result:0 for every int that I put as a parameter for the method.Please tell me where i went wrong.Thank you.

lenBs[0] is just getting:
integerBs[0] = (byte) ((i >>> 24) & 0xFF);
... which in the case of i = 4, integerBs[0] == 0.

Related

BSD checksum and bits operations explanation

I try understand BSD checksum calulcation algorithm, writed in Java language.
Wiki writed:
byte checksum(byte[] input) {
byte checksum = 0;
for (byte cur_byte: input) {
checksum = (byte) (((checksum & 0xFF) >>> 1) + ((checksum & 0x1) << 7)); // Rotate the accumulator
checksum = (byte) ((checksum + cur_byte) & 0xFF); // Add the next chunk
}
return checksum;
}
And my questions:
Why we use bitwise & in this line checksum = (byte) ((checksum + cur_byte) & 0xFF); ? 0xFF is binary "11111111" and this operation not return always this same number?
What is a sense of this operation? checksum = (byte) (((checksum & 0xFF) >>> 1) + ((checksum & 0x1) << 7)); I understand binary operation and logical and arithmetical shifts, but dont understand what we doing.
Thanks for help :)
b & 0xFF is often used to cast signed byte to bit-identical int. In this case it is unnecessary - (byte)(b & 0xFF) identical to (b). For example ((byte)-1) & 0xFF = 255
12345678 >>>1 01234567
12345678 <<7 80000000 ADD -> 81234567
Thus it is cyclic rotation

CRC16 code from Java to PHP [duplicate]

This question already has answers here:
How to calculate crc16 in php
(2 answers)
Closed 8 years ago.
How to convert the Java CRC16 code to PHP code? PHP doesn't accept byte and >>>
public static int CRC16(final byte[] buffer) {
int crc = 0xffff;
for (int i = 0; i < buffer.length; i++) {
crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
crc ^= (buffer[i] & 0xff);
crc ^= ((crc & 0xff) >> 4);
crc ^= (crc << 12) & 0xffff;
crc ^= ((crc & 0xff) << 5) & 0xffff;
}
crc &= 0xffff;
return crc;
}
Replace crc >>> 8 with (crc >> 8) & 0xff.

how to convert a string to byte array in java

Hi I have the following string
String msg = "9192939495"
And i want to create the bellow byte
byte[] texttoprint = {(byte) 0x91, (byte) 0x92,(byte) 0x93,(byte) 0x94,(byte) 0x95}
i try this
public static byte[] hexStringToByteArray(String s) {
/*String input = "0102FFAB";*/
byte[] data = new byte[s.length() / 2];
for( int i = 0; i < s.length(); i+=2)
{
data[i/2] = (byte) Integer.decode( "0x" + s.substring( i, i + 2 ) ).byteValue();
}
return data;
}
but it does not works
Also how can I print texttoprint at eclipse log in order to check if everything is OK?
PS if i send to printer {(byte) 0x91, (byte) 0x92,(byte) 0x93,(byte) 0x94,(byte) 0x95} everything is OK but if i sent the result of hexStringToByteArray nothing happens
static byte[] decode(final String enc) {
final long val = Long.parseLong(enc, 16);
final byte[] raw = new byte[] {
(byte) ((val & 0xff00000000000000L) >> 56),
(byte) ((val & 0xff000000000000L) >> 48),
(byte) ((val & 0xff0000000000L) >> 40),
(byte) ((val & 0xff00000000L) >> 32),
(byte) ((val & 0xff000000) >> 24),
(byte) ((val & 0xff0000) >> 16),
(byte) ((val & 0xff00) >> 8),
(byte) (val & 0xff)
};
final int n = enc.length() >> 1;
final byte[] trimmed = new byte[n];
System.arraycopy(raw, 8 - n, trimmed, 0, n);
return trimmed;
}
You can print the values using Arrays.toString to convert to text form. To verify they're equal, try using Arrays.equals.
System.out.println(Arrays.equals(texttoprint, hexStringToByteArray("9192939495"))
? "success" : "failure");

How to covert hex string to byte array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a string representation of a hex dump to a byte array using Java?
I am trying to convert a hex string "FFFFFFFFFFFFFFFF" into byte array with size 8
the result should be
byte[] mKey = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };
I have tried the for loop
public static byte[] HexString2Bytes(String src) {
byte[] res = new byte[8];
for (int i = 0; i < 16; i = i + 2) {
res[i] = convertToByte(src.substring(i, i + 2));
}
return res;
}
the problem is, I don't know how to implement the method convertToByte() to convert a hex string, like "FF" to 0xFF, please help, thanks.
int convertToByte(String s){
return Integer.parseString(s, 16);
}

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