zoukankan      html  css  js  c++  java
  • java中String byte HexString的转换

    
    HexString——>byte

       public static byte[] hexStringToBytes(String hexString) {
            if (hexString == null || hexString.equals("")) {
                return null;
            }
            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;
        }
        private static byte charToByte(char c) {
            return (byte) "0123456789ABCDEF".indexOf(c);
        }


    byte——>String
        
     public static String bytesToHexString(byte[] src){
            StringBuilder stringBuilder = new StringBuilder("");
            if (src == null || src.length <= 0) {
                return null;
            }
            for (int i = 0; i < src.length; i++) {
                int v = src[i] & 0xFF;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }
                stringBuilder.append(hv);
            }
            return stringBuilder.toString();
        }


    byte——>hexString

    public   String printHexString( byte[] b) {
    String a = "";
      for (int i = 0; i < b.length; i++) { 
        String hex = Integer.toHexString(b[i] & 0xFF); 
        if (hex.length() == 1) { 
          hex = '0' + hex; 
        }
       
        a = a+hex;
     
      
           return a;
    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。(转载请注明出自 AllenCoder)

  • 相关阅读:
    log4net的使用
    数据库概念及构成
    基于C#WPF框架——动画
    基于C# WPF框架的贪吃蛇
    使用Teigha.net读取CAD的常用功能模块
    Teigha.net实体属性注释
    .net(C#数据库访问) Mysql,Sql server,Sqlite,Access四种数据库的连接方式
    Delphi解析修改Json文件,基于superobject.pas(ISuperObject)
    C++结构体与Delphi结构体相互传参,结构体中包含结构体的嵌套,数组指针
    C++ Json解析CJsonObject的详细使用
  • 原文地址:https://www.cnblogs.com/allencoder/p/4830752.html
Copyright © 2011-2022 走看看