Friday, March 7, 2014

How to convert data types? byte [] -> int


Data on android casts the problem, I read from the file data exists byte [] b's memory.

There needs to be converted into four-byte int, 2 bytes turn into short.

If it is c + +, int i = * (int *) & b [0]; can.

Java should do it?
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
int byteArrToInt (byte [] b, int off) {
int value = 0;
for (int i = 0; i <4; i + +) {
int shift = (4 - 1 - i) * 8;
value + = (b [i + off] & 0x000000FF) << shift;
}
return value;
}
Reply:
To own the translation is a little cup ah, but probably no other convenient way to birds.

Reply:
.
 ByteBuffer.wrap (null) getShort (); 

Pay attention to your byte is big-end or little-end
Reply:
reference to the third floor youngc527 reply:
 ByteBuffer.wrap (null) getShort (); 
.
Pay attention to your byte is big-end or little-end


My binary data byte [] b, it seems that the variable b does not wrap methods exist?

How your ByteBuffer statement?

Reply:
 / ** 
* Get byte array corresponding to the first two bytes int value
* @ Param bytes
* @ Throws StringIndexOutOfBoundsException
* @ Return
* /
public static int byteArray2int (byte [] byteArray) throws StringIndexOutOfBoundsException {
int num = byteArray [0] & 0xFF;
num | = ((byteArray [1] << 8) & 0xFF00);
return num;
}

/ **
* Get byte array corresponding to the first four bytes int value (for low front, high in the post)
* @ Param bytes
* @ Throws StringIndexOutOfBoundsException
* @ Return
* /
public static int byteArray4intL (byte [] byteArray) throws StringIndexOutOfBoundsException {
int num = byteArray [0] & 0xFF;
num | = ((byteArray [1] << 8) & 0xFF00);
num | = ((byteArray [2] << 16) & 0xFF0000);
num | = ((byteArray [3] << 24) & 0xFF000000);
return num;
}

Reply:
http://www.360doc.com/content/06/0809/10 / 8473_177064.shtml
Reply:
 java.nio.ByteBuffer.wrap (bytes) getShort ();. 

No comments:

Post a Comment