首页 > 代码库 > 字节流、字符串、16进制字符串转换__Java(转)
字节流、字符串、16进制字符串转换__Java(转)
Java代码
- /**
- * @Package:
- * @ClassName:TypeConversion
- * @Description:字节流、字符串、16进制字符串转换
- * @author:xk
- * @date:Jan 8, 2013 5:00:08 PM
- */
- public class TypeConversion {
- /**
- * @Title:bytes2HexString
- * @Description:字节数组转16进制字符串
- * @param b
- * 字节数组
- * @return 16进制字符串
- * @throws
- */
- public static String bytes2HexString(byte[] b) {
- StringBuffer result = new StringBuffer();
- String hex;
- for (int i = 0; i < b.length; i++) {
- hex = Integer.toHexString(b[i] & 0xFF);
- if (hex.length() == 1) {
- hex = ‘0‘ + hex;
- }
- result.append(hex.toUpperCase());
- }
- return result.toString();
- }
- /**
- * @Title:hexString2Bytes
- * @Description:16进制字符串转字节数组
- * @param src
- * 16进制字符串
- * @return 字节数组
- * @throws
- */
- public static byte[] hexString2Bytes(String src) {
- int l = src.length() / 2;
- byte[] ret = new byte[l];
- for (int i = 0; i < l; i++) {
- ret[i] = (byte) Integer
- .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
- }
- return ret;
- }
- /**
- * @Title:string2HexString
- * @Description:字符串转16进制字符串
- * @param strPart
- * 字符串
- * @return 16进制字符串
- * @throws
- */
- public static String string2HexString(String strPart) {
- StringBuffer hexString = new StringBuffer();
- for (int i = 0; i < strPart.length(); i++) {
- int ch = (int) strPart.charAt(i);
- String strHex = Integer.toHexString(ch);
- hexString.append(strHex);
- }
- return hexString.toString();
- }
- /**
- * @Title:hexString2String
- * @Description:16进制字符串转字符串
- * @param src
- * 16进制字符串
- * @return 字节数组
- * @throws
- */
- public static String hexString2String(String src) {
- String temp = "";
- for (int i = 0; i < src.length() / 2; i++) {
- temp = temp
- + (char) Integer.valueOf(src.substring(i * 2, i * 2 + 2),
- 16).byteValue();
- }
- return temp;
- }
- /**
- * @Title:char2Byte
- * @Description:字符转成字节数据char-->integer-->byte
- * @param src
- * @return
- * @throws
- */
- public static Byte char2Byte(Character src) {
- return Integer.valueOf((int)src).byteValue();
- }
- /**
- * @Title:intToHexString
- * @Description:10进制数字转成16进制
- * @param a 转化数据
- * @param len 占用字节数
- * @return
- * @throws
- */
- private static String intToHexString(int a,int len){
- len<<=1;
- String hexString = Integer.toHexString(a);
- int b = len -hexString.length();
- if(b>0){
- for(int i=0;i<b;i++) {
- hexString = "0" + hexString;
- }
- }
- return hexString;
- }
- public static void main(String args[]) {
- System.out.println(hexString2String("3133383131313536373838"));
- }
- }
转自:http://hunray.iteye.com/blog/1849585
字节流、字符串、16进制字符串转换__Java(转)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。