常用的数据转换工具类

在开发过程中有时会经常需要做数据转换,最经常使用的就是对接一些硬件设备。硬件设备通讯一般都是使用字节数组,十六进制数据,二进制数据等。

/*
 * Create 7/18 by xwj
 * 数据处理,进制转换等常用工具类
 */
public class DataTreater {

public static String byte2String(byte[] bytes, int icnt) {
    //转化byte[]为常用参数十进制字符串
    Integer tempData = Integer.valueOf(formatBytes(bytes), 16);
    String tempStr = tempData.toString();

    for (int i = 0; i < icnt - tempData.toString().length(); ++i) {
        tempStr = "0" + tempStr;
    }

    return tempStr;
}

public static String hexToinvalue(byte[] src, int offset) {
    //十六进制数组转化为十进制小数
    int invalue = bytesToInt(src, offset);
    return IntStrToAmountStr(invalue + "");
}

public static int bytesToInt(byte[] src, int offset) {
    int value;
    value = (int) ((src[offset] & 0xFF)
            | ((src[offset + 1] & 0xFF) << 8));
    return value;
}

public static int bytesToInt(byte src) {
    int value;
    value = (int) (src & 0xFF);
    return value;
}

public static String BCD2String(byte[] bytes) {
    StringBuffer temp = new StringBuffer(bytes.length * 2);

    for (int i = 0; i < bytes.length; ++i) {
        temp.append((byte) ((bytes[i] & 240) >>> 4));
        temp.append((byte) (bytes[i] & 15));
    }

    return temp.toString();
}

public static byte decimalToBinary(int decimalSource) {
    BigInteger bi = new BigInteger(String.valueOf(decimalSource));
    return bit2byte(bi.toString(2));
}

public static byte bit2byte(String bString) {
    byte result = 0;
    int i = bString.length() - 1;

    for (int j = 0; i >= 0; ++j) {
        result = (byte) ((int) ((double) result + (double) Byte.parseByte(String.valueOf(bString.charAt(i))) * Math.pow(2.0D, (double) j)));
        --i;
    }

    return result;
}

public static String HexStrToAmountStr(String s) {
    long Amount = Long.parseLong(s, 16);
    String d = String.valueOf(Amount / 100L);
    if (Amount % 100L < 10L) {
        d = d + ".0" + Amount % 100L;
    } else {
        d = d + "." + Amount % 100L;
    }

    return d;
}

public static String IntStrToAmountStr(String intstr) {
    int amount = Integer.valueOf(intstr);
    String d = String.valueOf(amount / 10);
    d = d + "." + amount % 10;

    return d;
}

public static String toStringHex(String s) {
    byte[] baKeyword = new byte[s.length() / 2];

    for (int i = 0; i < baKeyword.length; ++i) {
        try {
            baKeyword[i] = (byte) (255 & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
        } catch (Exception var5) {
            var5.printStackTrace();
        }
    }

    try {
        s = new String(baKeyword, "utf-8");
    } catch (Exception var4) {
        var4.printStackTrace();
    }

    return s;
}

public static short[] toShortArray(byte[] src) {
    //byte数组转化为short数组
    int count = src.length >> 1;
    short[] dest = new short[count];
    for (int i = 0; i < count; i++) {
        dest[i] = (short) (((src[i * 2 + 1] & 0x00FF) << 8) | (src[2 * i] & 0x00FF));
    }
    return dest;
}

public static short toShort(String hexstr) {
    return (short) Integer.parseInt(hexstr, 16);
}

public static int byteArrayToShort(byte[] b) {
    return (b[0] << 8)
            + (b[1] & 0xFF);
}

public static short byteToShort(byte high, byte low) {
    return (short) (((high << 8) & 0xFF00) | (low & 0xFF));
}

public static String bytesToHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < bytes.length; ++i) {
        String hex = Integer.toHexString(255 & bytes[i]);
        if (hex.length() == 1) {
            sb.append('0');
        }

        sb.append(hex);
    }

    return sb.toString();
}

public static byte[] hexStringToBytes(String hexString) {
    if (hexString != null && !hexString.equals("")) {
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];

        for (int i = 0; i < length; ++i) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }

        return d;
    } else {
        return null;
    }
}

private static byte charToByte(char c) {
    return (byte) "0123456789ABCDEF".indexOf(c);
}

public static String formatBytes(byte[] p_arrBytes) {
    //转化byte[]为十六进制字符串
    return formatBytes(p_arrBytes, p_arrBytes.length, "");
}

public static String byteToHexStr(byte b) {
    //字节转换为16进制字符
    String hex = Integer.toHexString(b & 0xFF);
    if (hex.length() == 1) {
        hex = '0' + hex;
    }
    return hex.toUpperCase();
}

public static void printHexString(byte[] b) {
    //字节数组转换为16进制字符串
    for (int i = 0; i < b.length; i++) {
        byte hex = b[i];
    }
}


public static String toHexString(byte b) {
    String s = Integer.toHexString(b & 0xFF);
    if (s.length() == 1) {
        return "0" + s;
    } else {
        return s;
    }
}

public static String formatBytes(byte p_Bytes) {
    StringBuffer sbResult = new StringBuffer();
    int intValue = p_Bytes;
    if (p_Bytes < 0) {
        intValue = p_Bytes + 256;
    }

    String strHexString = Integer.toHexString(intValue);
    if (strHexString.length() == 1) {
        sbResult.append("0");
    }

    sbResult.append(strHexString);
    return sbResult.toString();
}

public static String formatBytes(byte[] p_arrBytes, int p_intLength, String p_strSeparator) {
    StringBuffer sbResult = new StringBuffer();

    for (int intIndex = 0; intIndex < p_intLength; ++intIndex) {
        int intValue = p_arrBytes[intIndex];
        if (intValue < 0) {
            intValue += 256;
        }

        String strHexString = Integer.toHexString(intValue);
        if (strHexString.length() == 1) {
            sbResult.append("0");
            sbResult.append(p_strSeparator);
        }

        sbResult.append(strHexString);
    }

    return sbResult.toString();
}

public static byte[] compress2To1InBytes(String p_strValue) throws Exception {
    int intLength = p_strValue.length();
    int intCounter = 0;
    int intResultLength = intLength / 2 + (intLength % 2 != 0 ? 1 : 0);
    byte[] arrResult = new byte[intResultLength];

    for (int intIndex = intLength; intIndex >= 1; intIndex -= 2) {
        int intValue;
        if (intIndex == 1) {
            intValue = Integer.parseInt(p_strValue.substring(intIndex - 1, intIndex));
        } else {
            intValue = Integer.parseInt(p_strValue.substring(intIndex - 2, intIndex));
        }

        arrResult[intResultLength - intCounter - 1] = (byte) (intValue + 33);
        ++intCounter;
    }

    return arrResult;
}

public static String compress2To1(String p_strValue) throws Exception {
    return compress2To1(p_strValue, "iso8859_1");
}

public static String compress2To1(String p_strValue, String p_strEncoding) throws Exception {
    return new String(compress2To1InBytes(p_strValue), p_strEncoding);
}
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Java中字符串编码转换工具类可以通过使用Java自带的Charset类和String类的getBytes()方法来实现。下面是一个示例的工具类: ```java import java.nio.charset.Charset; public class EncodingUtils { // 将指定编码的字符串转换为默认编码的字符串 public static String convertToDefaultEncoding(String str, String sourceEncoding) { byte[] bytes = str.getBytes(Charset.forName(sourceEncoding)); return new String(bytes); } // 将默认编码的字符串转换为指定编码的字符串 public static String convertToEncoding(String str, String targetEncoding) { byte[] bytes = str.getBytes(); return new String(bytes, Charset.forName(targetEncoding)); } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { String str1 = "中文字符串"; // 将UTF-8编码的字符串转换为默认编码的字符串 String defaultEncodingStr = EncodingUtils.convertToDefaultEncoding(str1, "UTF-8"); System.out.println("Default Encoding: " + defaultEncodingStr); // 将默认编码的字符串转换为GBK编码的字符串 String targetEncodingStr = EncodingUtils.convertToEncoding(defaultEncodingStr, "GBK"); System.out.println("Target Encoding: " + targetEncodingStr); } } ``` 在上述示例中,工具类`EncodingUtils`提供了两个静态方法。`convertToDefaultEncoding()`方法将指定编码的字符串转换为默认编码的字符串,而`convertToEncoding()`方法将默认编码的字符串转换为指定编码的字符串。 ### 回答2: Java字符串编码转换工具类是一种用于处理字符串编码转换工具类,它可以将字符串从一种字符编码转换为另一种字符编码。在Java中,字符串的编码可以使用标准的UTF-8、UTF-16、ISO-8859-1等编码方式。 这个工具类通常提供以下几种方法: 1. `toUTF8(String str)`:将字符串从其他编码转换为UTF-8编码。 2. `fromUTF8(String str)`:将UTF-8编码的字符串转换为其他编码。 3. `toISO88591(String str)`:将字符串从其他编码转换为ISO-8859-1编码。 4. `fromISO88591(String str)`:将ISO-8859-1编码的字符串转换为其他编码。 使用这个工具类可以避免在转换编码时出现乱码或者字符串不可识别的问题。例如,当我们从外部资源读取数据时,如果字符串的编码与程序默认字符编码不一致,就会导致乱码,这时可以使用这个工具类进行编码转换。 在实现这个工具类时,可以使用Java提供的相关类库,如`java.nio.charset.Charset`、`java.nio.CharBuffer`等类来进行编码转换操作。首先,通过指定源编码和目标编码,创建`Charset`对象;然后,使用`encode`方法将源字符串编码成字节序列,并使用目标`Charset`对象的`decode`方法将字节序列解码成目标编码的字符串。 使用这个工具类时,需要注意的是源编码和目标编码必须是支持的字符编码,否则会抛出编码不支持的异常。此外,还应该注意对输入的异常情况进行处理,例如空字符串或空指针异常,以确保程序的健壮性。 总之,Java字符串编码转换工具类是一个方便实用的工具,可以帮助我们在不同编码间进行转换,避免乱码的问题,提高程序的稳定性和可靠性。 ### 回答3: Java提供了许多内置的工具类来方便字符串编码转换。其中最常用工具类是`java.nio.charset.Charset`和`java.lang.String`类。 首先,`Charset`类包含了许多常见的字符集,比如UTF-8、GBK、ISO-8859-1等。我们可以使用`Charset.forName(String charsetName)`方法来获取指定字符集的一个实例。 接下来,`String`类提供了几个方法来进行字符串编码转换。其中最常用的是`getBytes(String charsetName)`方法,它将字符串按照指定的字符集转换为字节数组。例如,如果我们想将字符串转换为UTF-8编码的字节数组,可以使用`getBytes("UTF-8")`方法。 除了将字符串转换为字节数组,`String`类还提供了`getBytes()`方法,它将字符串按照默认的字符集转换为字节数组。默认的字符集可以通过调用`Charset.defaultCharset()`方法获取。 另外,如果我们想将字节数组转换为字符串,可以使用`String`类的构造方法`String(byte[] bytes, Charset charset)`。该构造方法将字节数组按照指定的字符集转换为字符串。 除了上述的方法,还有一些其他的工具类可以辅助字符串编码转换。比如,`java.io.InputStreamReader`和`java.io.OutputStreamWriter`类提供了将字节流与字符流进行转换的功能。 总结来说,Java提供了丰富的工具类来进行字符串编码转换。我们可以通过`Charset`类获取指定字符集的实例,通过`String`类的相关方法来进行字符串与字节数组之间的转换。另外,还可以使用`java.io.InputStreamReader`和`java.io.OutputStreamWriter`类进行字节流与字符流之间的转换。这些工具类的使用可以方便地实现字符串编码转换的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiawj8957

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值