几种字符间的转换
1.将字符串转换成固定长度的字符串
public static String getFixedLenStr(String str, int len, char c, boolean fillleft) { if (str == null) str = ""; if (str.getBytes().length > len) return str.substring(0, len); else { int len1 = len - str.getBytes().length; if (len1 > 0) { byte[] b = new byte[len1]; for (int i = 0; i < len1; i++) b[i] = (byte) c; if (fillleft) str = new String(b) + str; else str += new String(b); } return str; } }
2.将一个字节转换为16进制字符串
public static String convertByteToHexStr(byte src) { byte[] ret = new byte[2]; ret[0] = (byte) (src >> 4 & 0x0F); ret[0] = (byte) (ret[0] > 9 ? (ret[0] - 10 + 'a') : (ret[0] + '0')); ret[1] = (byte) (src & 0x0F); ret[1] = (byte) (ret[1] > 9 ? (ret[1] - 10 + 'a') : (ret[1] + '0')); return new String(ret); }
3.将十六进制字符串转换成一个字节
static public byte convertHexStrToByte(String src) { byte b1 = '0', b2 = '0'; byte[] b = src.getBytes(); src = src.toLowerCase(); if (b.length > 1) { b2 = b[1]; b1 = b[0]; } else if (b.length > 0) b2 = b[0]; b1 = (byte) (b1 > '9' ? b1 - 'a' + 10 : b1 - '0'); b2 = (byte) (b2 > '9' ? b2 - 'a' + 10 : b2 - '0'); return (byte) (b1 << 4 | b2); }