First, only string is associated with the encoding;
When converting between byte and other types, be aware of big or small endpoints.
Encoding: Ascii Unicode gbk utf-8 et cetera
A byte of 8 digits can be composed of two 16-digit (0XFF), a 16-bit 4-digit, or 8-bit binary number, which has nothing to do with coding, but can be expressed in 2 or other systems.
16 binary strings such as "0xFF" converted to 16 binary byte
String[] s= "0X0C 0x03 0X00 0X04 0X00 0X02 0x84 0xd7". Replace ("X", "X"). Split ("");
Byte[] B=new byte[s.length];
for (int i=0;i<s.length;i++) {
b[i]= (byte) integer.parseint (S[i].substring (2);
}
System.out.println (arrays.tostring (b));
Convert byte[n] to string;
New String (Byte[n],0,length, "GBK");
Float is 4 bytes, float is converted to byte type
It's all done by shifting.
4byte Convert to float
Left shift
/**
* Byte to floating-point
*
* @param b bytes (at least 4 bytes)
* @param index start position
* @return
*/
public static float byte2float (byte[] B, int index) {
int l;
L = b[index + 0];
L &= 0xFF;
L |= ((long) B[index + 1] << 8);
L &= 0xFFFF;
L |= ((long) B[index + 2] << 16);
L &= 0xFFFFFF;
L |= ((long) B[index + 3] << 24);
Return Float.intbitstofloat (L);
}
Float converted into 4byte
Right Shift/**
* Floating-point conversions to bytes
*
* @param F
* @return
*/
public static byte[] Float2byte (float f) {
Convert float to byte[]
int fbit = Float.floattointbits (f);
Byte[] B = new Byte[4];
for (int i = 0; i < 4; i++) {
B[i] = (byte) (Fbit >> (24-i * 8));
}
Flip an array
int len = b.length;
Creates an array of the same type as the source array element
byte[] Dest = new Byte[len];
To prevent modifying the source array, copy the source array to a copy
System.arraycopy (b, 0, dest, 0, Len);
byte temp;
Exchange the first and last of the first
for (int i = 0; i < LEN/2; ++i) {
temp = Dest[i];
Dest[i] = dest[len-i-1];
Dest[len-i-1] = temp;
}
return dest;
}