About byte float string encoding 16 binary string to 16 binary byte __java code and algorithm

Source: Internet
Author: User

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;

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.