有一个二进制文件,把它按字节读入到字节数组中,要求输出十六进制数,怎么办呢?

解决方案 »

  1.   

    如果自己实现的话,可以用0x0F和0xF0分别对byte进行与操作,然后转换为对应16进制数字
      

  2.   

    可以转换为Integer然后使用toString(int i, int radix) 
      

  3.   

    没有现成的函数,我自己做了一个。/**
         * 将二进制数据编码为存储十六进制数形式的文本。
         * @param buf 要编码的数据。
         * @return 编码后的文本。 
         */
        public static String BinToHex( byte[] buf )
    {
         final char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; 
        
    if( buf.length < 1 ) return "";

    StringBuffer result = new StringBuffer( buf.length * 2 );
    for( int i = 0; i < buf.length; i++ )
    {
    result.append( digit[(buf[i]>>4&0x0F)] );
    result.append( digit[(buf[i]&0x0F)] );
    } return result.toString();
    }

        /**
         * 将存储十六进制数的文本解码为二进制数据。
         * @param sText 要解码的文本。
         * @return 解码后的数据,如果解码失败则为<code>null</code>。
         * @throws IllegalArgumentException 在存储十六进制数的文本有无效的字符时抛出。
         */
        public static byte[] HexToBin( String sText ) throws IllegalArgumentException
    {
    byte[] hex = sText.getBytes();
    int textSize = hex.length;
    if( textSize < 1 ) return null;

    byte[] result = new byte[textSize/2];

    for( int i = 0; i < textSize; i += 2 )
    {
    if( hex[i] >= '0' && hex[i] <= '9' ) result[i/2] = (byte)( (hex[i]-48) << 4 & 0xF0 );
    else if( hex[i] >= 'A' && hex[i] <= 'F' ) result[i/2] = (byte)( (hex[i]-55) << 4 & 0xF0 );
    else if( hex[i] >= 'a' && hex[i] <= 'f' ) result[i/2] = (byte)( (hex[i]-87) << 4 & 0xF0 );
    else throw new IllegalArgumentException( "有无效的字符!" ); 

    if( hex[i+1] >= '0' && hex[i+1] <= '9' ) result[i/2] |= (byte)( (hex[i+1]-48) & 0xF );
    else if( hex[i+1] >= 'A' && hex[i+1] <= 'F' ) result[i/2] |= (byte)( (hex[i+1]-55) & 0xF );
    else if( hex[i+1] >= 'a' && hex[i+1] <= 'f' ) result[i/2] |= (byte)( (hex[i+1]-87) & 0xF );
    else throw new IllegalArgumentException( "有无效的字符!" );
    } return result;
    }