| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- package com.mes.util;
- public class DataUtils {
- // 将16进制字符串转化为byte数组
- public static byte[] hexStringToByteArray(String s) {
- s = s.replace(" ", "");
- int len = s.length();
- byte[] data = new byte[len / 2];
- for (int i = 0; i < len; i += 2) {
- data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
- + Character.digit(s.charAt(i + 1), 16));
- }
- return data;
- }
- public static int getBit(int data, int index) {
- return (data >> index) & 1;
- }
- public static int bytesToInt(byte[] data) {
- int a = 0;
- for (int i = 0; i < data.length; i++) {
- a = a | (data[i] & 0xFF) << (8 * i);
- }
- return a;
- }
- // 将一个byte值转换成16进制形式的字符串
- public static String byteToHexString(byte b) {
- // 得到高4位和低4位的数字
- int high = (b & 0xF0) >>> 4; // 高4位
- int low = b & 0x0F; // 低4位
- // 将高4位和低4位转换为16进制字符
- return hexChar(high) + String.valueOf(hexChar(low));
- }
- public static String CRC16(String input) {
- byte[] bytes = hexStringToByteArray(input);
- // 初始化CRC寄存器
- int crc = 0xFFFF;
- for (byte b : bytes) {
- // 更新CRC寄存器
- crc ^= (b & 0xFF);
- for (int i = 0; i < 8; i++) {
- if ((crc & 0x0001) != 0) {
- crc >>= 1;
- crc ^= 0xA001;
- } else {
- crc >>= 1;
- }
- }
- }
- // 获取CRC16结果的高位和低位
- byte high = (byte) ((crc >> 8) & 0xFF);
- byte low = (byte) (crc & 0xFF);
- // 将CRC16结果添加到原始字符串后面
- return input + " " + byteToHexString(low) + " " + byteToHexString(high);
- }
- // 把int数据转化为Word,一个Word有两字节, 且低位在前、高位在后
- public static String intToWord(int n) {
- byte b1 = (byte) (n & 0xFF);
- byte b2 = (byte) ((n >> 8) & 0xFF);
- String s1 = byteToHexString(b1);
- String s2 = byteToHexString(b2);
- return s1 + " " + s2;
- }
- // 辅助方法:根据数字返回对应的16进制字符
- private static char hexChar(int n) {
- if (n >= 0 && n <= 9) {
- return (char) ('0' + n);
- } else if (n >= 10 && n <= 15) {
- return (char) ('A' + (n - 10));
- }
- throw new IllegalArgumentException("转换为十六进制字符的值无效: " + n);
- }
- }
|