import java.text.DecimalFormat;
/**
* Created by zry on 18/3/7.
*/
public class DataUtil {
/**
* 保留浮点数小数点后面几位
*
* @param f 浮点数
* @param format 浮点数的格式
* @return
*/
public static String formatFloat(float f, String format) {
DecimalFormat df = new DecimalFormat(format);
return df.format(f);
}
/**
* 将两个字节拼接还原成有符号的整型数据
数据域中的数据都按小端存储,示例:数据0x1234,则Byte0为0x34,Byte1为0x12
*
* @param byte1
* @param byte2
* @return
*/
public static int pinJie2ByteToInt(byte byte1, byte byte2) {
int result = byte1;
result = (result << 8) | (0x00FF & byte2);
return result;
}
/**
* 整型数据拆分为长度为2的字节数组,低8位存放在序号小的元素,高8位存放在序号大的元素中(小端存储)
*
* @param data
* @return
*/
public static byte[] chaiFenDataIntTo2Byte(int data) {
byte[] byteArray = new byte[2];
byteArray[0] = (byte) data;
byteArray[1] = (byte) (data >> 8);
return byteArray;
}
/**
* 将byte数组转成十六进制形式的字符串
*
* @param src
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (byte aSrc : src) {
int v = aSrc & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
stringBuilder.append(' ');
}
return stringBuilder.toString();
}
/**
* 取字节的后5位[4:0]表示斜率
*
* @param xoctByte
* @return
*/
public static int getXoctInt(byte xoctByte) {
//或上 & 0x1F 取后五位
int result = xoctByte & 0x1F;
return result;
}
/**
* 将斜率整型0-8 添加到字节的[4:0]位上去
*
* @param xoctInt
* @return
*/
public static byte setIntXoctToByte(byte xoctByte, int xoctInt) {
//先取int的后五位保留
byte byteInt = (byte) xoctInt;
byteInt = (byte) (byteInt & 0x1F);//取后五位
//保留原先byte的前两位
xoctByte = (byte) (xoctByte & 0xC0);
//将前两位与后五位拼接形成一个新的,按需求要的byte
xoctByte = (byte) (xoctByte | byteInt);
return xoctByte;
}
/**
* 取字节的前两位[7:6]表示类型
*
* @param xoctByte
* @return
*/
public static int getTypeInt(byte xoctByte) {
int result = (xoctByte >> 6) & 0x03;
return result;
}
/**
* 将斜率整型0-3 添加到字节的[7:06]位上去
*
* @param xoctInt
* @return
*/
public static byte setIntTypeToByte(byte xoctByte, int xoctInt) {
byte byteInt = (byte) xoctInt;
byteInt = (byte) ((byteInt & 0x03) << 6);
//保留原先byte的后五位
xoctByte = (byte) (xoctByte & 0x1F);
//将前两位与后五位拼接形成一个新的,按需求要的byte
xoctByte = (byte) (xoctByte | byteInt);
return xoctByte;
}
}
java字节运算,拼接两个byte和和将一个int拆分成两个byte,byte取高位和取低位运算。
最新推荐文章于 2024-05-09 17:24:38 发布