- String 转换成byte
String str = "abcd12"; byte[] a = str.getBytes(); System.out.println(a); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); }
- byte 转换成String
String btstr = new String(a); System.out.println(btstr);
- String 转换成字节对齐的byte ,下面例子采用4字节对齐
//字节对齐,不足位在高位补零 public static void bytePadding(String src) { int strlen = src.length(); int addNum = strlen % 4;//四字节对齐 int length; int offset; if (addNum != 0) { length = strlen + (4 - addNum); offset = 4 - addNum; } else { length = strlen; offset = 0; } byte[] buf = new byte[length]; System.out.println(length + " : " + addNum); StringToByte(src, offset, buf); } //转换成byte方法 public static void StringToByte(String src, int offset, byte[] dest) { byte[] arrays = src.getBytes(); System.arraycopy(arrays, 0, dest, offset, arrays.length); for (int i = 0; i < dest.length; i++) { System.out.print(dest[i] + " "); } } //测试 public static void main(String[] args) { bytePadding("abcdef"); }
- byte转换成String和第二个步骤一样
- 上面所有例子的结果如下:
1.[B@de6ced
97 98 99 100 49 50
2.abcd12
3.0 0 97 98 99 100 101 102
4.abcdef