Mar 18 2008

Hex转换

Category: 技术ssmax @ 21:28:58

n年前的课题了,今天要用,都忘记了,记录一下

byte to hex 直接java方法:

// convert a single byte b to a 2-char hex string
// with possible leading zero.
String s2 = Integer.toString( ( b & 0xff ) + 0x100, 16 /* radix */ )
		.substring( 1 );

字典法和反向转换,记录自己在无线时候写的一个:

        /*
         *取得byte的16进制字符串
        */     
        private static final String HexString = “0123456789ABCDEF”;
       

        public static String getHexString(byte [] msg_byte)
        {
                StringBuffer sb = new StringBuffer(msg_byte.length * 2);
                for(int i =0;i<msg_byte.length;i++)
                {
                        sb.append(HexString.charAt(0xf&msg_byte[i]>>4)).append(HexString.charAt(msg_byte[i]&0xf));
                }
                return sb.toString();
        }      
               
        public static byte[] getBytesFromHexStr(String s)
        {              
                try    
                {              
                        int i = s.length();
                        byte result[] = new byte[i >> 1];
                        for(int k = 0; k < i;)
                                result[k >> 1] = (byte)(Integer.parseInt(s.substring(k,k+=2),16));
                        return result;
                }
                catch(Exception ex)
                {
                        //ex.printStackTrace();
                        return null;
                }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.