繁体   English   中英

将String转换为它表示的十六进制值

[英]Converting String to the Hexadecimal-value it represents

这一直让我发疯,因为我知道有一个简单的解决方案,但我找不到它...

我有一个要求十六进制数字的edittext字段,该文本字段仅限于接收0-9,a,b,c,d,e,f。

如何将此字符串转换为实际数字?

示例:字符串= 0F => int = 0F或可能=> 0000 1111。

我试图存储MAC地址,然后对其进行操作,但我只知道如何将字符串存储到SQLite中! :)

Integer.parseInt(String s, int radix)是您想要的。 传入16作为基数。 在此处阅读文档

对于MAC地址,您可能会发现Integer类型不够大,因此请尝试使用Long等效项。

而且,即使Long不够大,或者您想要任意大的精度,也可以使用BigInteger 您可以将基数传递给构造函数: public BigInteger(String val, int radix)

为了获得更大的灵活性,请查看Apache Commons提供的IntegerValidator

对于均匀长度的字符串

public static byte[] hexStringToByteArray(String str) {
try {


    String s = str;
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        if (i == len - 1) {
             System.out.println("in correct");                   
        } else {

            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));


        }
    }
    return data;
} catch (StringIndexOutOfBoundsException sex) {

    writeDirtyData(str.substring(0, str.indexOf(",")));
}
return null;

}

非奇数的十六进制字符串是正确的 从中检查源是否获得此字符串。 这是由于限制字符数而导致的字符串截断。 如果String是图像存储在数据库中,则使用程序而不使用任何工具来检索它

我在使用.net和MSSQL时遇到了同样的问题,并且通过使用webservice和Java Client,我尝试了所有转换和库,包括axis和util jpg

我不知道我遇到过多少次。 所以我写了这个类,可以用Hex操纵做很多事情。 从字节数组转到十六进制,ASCII ...只是高或低笔尖...

/**
 * Utility class for hexadecimal conversions.
 *
 * @author john.matthews
 *
 */
public class Hex {
    /** Array of bytes with the Hex values representing ASCII characters '0' thru '9' and 'A' thru 'F' */
    private static byte HEX_BYTE_MAP[] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46};

    /** Array of chars with the values '0' thru '9' and 'A' thru 'F' */
    private static char HEX_CHAR_MAP[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * Returns a string representation of the specified range of bytes in a byte array.
     * The hexadecimal value of each byte is converted to its ASCII representation and 
     * followed by a space.  <pre>For example: x'327F' ==> "32 7F "</pre>
     *
     * @param b - byte array containing the byte(s) to convert
     * @param offset - starting position in the array (0 being the leftmost position)
     * @param n - length or number of bytes to convert
     * @return string representing the bytes specified
     */
    public static String toHex(byte b[], int offset, int n) {
        int end = Math.min(offset+n, b.length);
        StringBuffer buffer = new StringBuffer();

        for(int i=offset; i<end; i++) {
            buffer.append(toHex(b[i]));
            buffer.append(" ");
        }

        return buffer.toString();
    }

    /**
     * Returns a string representation of all the bytes in a byte array.  The
     * hexadecimal value of each byte is converted to its ASCII representation and 
     * followed by a space.  <pre>For example: x'327F' ==> "32 7F "</pre>
     *
     * @param b - byte array to convert
     * @return string representing the bytes in the array
     */
    public static String toHex(byte b[]) {
        if(b==null)
            return "(null)";

        return toHex(b, 0, b.length);
    }

    /**
     * Returns a string representation of byte passed to this method. The
     * hexadecimal value of the byte is converted to its ASCII representation.
     * <pre>For example: x'7F' ==> "7F"</pre>
     * 
     * @param b - byte to convert
     * @return string representation of the byte
     */
    public static String toHex(byte b) {
          // Build an array of the characters corresponding to the left and right hex digits (nibbles)
          char[] array = { HEX_CHAR_MAP[(b >> 4) & 0x0f], HEX_CHAR_MAP[b & 0x0f] };

          return new String(array);
       }

    /**
     * Returns a string representation of character passed to this method. The
     * ASCII value of the character is converted to its hexadecimal representation
     * and is prefixed with two zeros.
     * <pre>For example: "N" ==> "004E"</pre>
     * 
     * @param c - character to convert
     * @return string representation of the character
     */
    public static String toHex(char c) {
              // The shifting right 8 bits for the hi byte results in 0!
              byte hi = (byte) (c >>> 8);
              // The lo byte contains the hex value for the character
              byte lo = (byte) (c & 0xff);

              return toHex(hi) + toHex(lo);
       }

    /**
     * Returns a string representation of the specified range of bytes in a byte array.
     * The hexadecimal value of each byte is used to look up its corresponding ASCII
     * character for display. Any nulls (value of x'00') are removed.
     * <pre>For example: x'31006A' ==> "1j"</pre>
     * 
     * @param b - byte array containing the byte(s) to convert
     * @param start - starting position in the array (0 being the leftmost position)
     * @param length - number of bytes to convert
     * @return string representing the bytes specified
     */
    public static String toASCII(byte b[], int start, int length) {
           StringBuffer asciiString = new StringBuffer();

           for (int i = start;i<(length+start);i++){
               // exclude nulls from the ASCII representation
               if (b[i] != (byte)0x00) {
                   asciiString.append((char)b[i]);
               }
           }

           return asciiString.toString();
       }


   /**
    * Returns a byte array with hexadecimal values of the specified ASCII representation
    * string.  Starting characters "0x" in the string are not converted.  Odd sized strings
    * will be padded with a zero for the leftmost nibble. 
    * <pre>For example: "0xF310D6A" ==> x'0F310D6A'</pre>
    * 
    * @param str - string to convert
    * @return byte array with hex values
    */
   public static byte[] toBytes(String str) {
       StringBuffer convString;

       // Remove hex prefix of "0x" if exists
       if (str.length() > 1 && str.toLowerCase().startsWith("0x")) {
           convString = new StringBuffer(str.substring(2));
       }
       else {
           convString = new StringBuffer(str);
       }

       // For odd sized strings, pad on the left with a 0
       if (convString.length() % 2 == 1) {
           convString.insert(0, '0');
       }

       byte[] result = new byte[convString.length() / 2];

       for (int i = 0; i < convString.length(); i += 2) {
           result[i/2] = (byte) (Integer.parseInt(convString.substring(i, i + 2), 16) & 0xFF);
       }

       return result;
   }

    /**
     * Converts an ASCII representation of a hexadecimal value into an actual hexadecimal byte.
     * <pre>For Example: hi="F" lo="8" ==> x'F8'</pre>
     * 
     * @param hi - high nibble or left hex digit in ASCII format
     * @param lo - low nibble or right hex digit in ASCII format
     * @return byte in hexadecimal format
     */
    public static byte fromASCII(byte hi, byte lo) {
        return (byte)Integer.parseInt(new String(new byte[]{hi,lo}), 16);
    }

    /**
     * Returns the decimal value of the specified range of ASCII represented 
     * hexadecimal nibbles.
     * <pre>For Example: x'007D' ==> "125"</pre>
     * 
     * @param asciiRepArray - array containing the bytes of ASCII to convert 
     * @param startPos - starting position in the array (0 being the leftmost position)
     * @param length - number of bytes to convert
     * @return string representation of the decimal value
     */
    public static String fromASCII(byte[] asciiArray, int startPos, int length) {
        int value = Integer.parseInt(Bytes.subsetAsString(asciiArray, startPos, length), 16);
        return "" + value;
    }

    /**
     * Returns the decimal value of the specified range of ASCII represented 
     * hexadecimal nibbles.  The returned string will be padded with leading
     * zeros for the specified number of digits.
     * <pre>For Example: x'007D', 4 digits ==> "0125"</pre>
     * 
     * @param asciiRepArray - array containing the bytes of ASCII to convert 
     * @param startPos - starting position in the array (0 being the leftmost position)
     * @param length - number of bytes to convert
     * @param digits - number of digits the result should have
     * @return string representation of the decimal value
     */
    public static String fromASCII(byte[] asciiArray, int startPos, int length, int digits) {
        String prePaddedValue = fromASCII(asciiArray, startPos, length);
        String padding = new String();

        for (int i = prePaddedValue.length(); i < digits; i++) {
            padding += "0";
        }

        return padding + prePaddedValue;
    }

    /**
     * Converts a hexadecimal value's high nibble into an ASCII representation byte.
     * <pre>For Example: x'F8' ==> "F"</pre>
     * 
     * @param hexByte - byte with the desired hex value
     * @return byte in ASCII format representing the left hex digit
     */
    public static byte nibHiToASCII(byte hexByte) {
        return HEX_BYTE_MAP[(hexByte & 0xF0)>>4];
    }

    /**
     * Converts a hexadecimal value's low nibble into an ASCII representation byte.
     * <pre>For Example: x'F8' ==> "8"</pre>
     *  
     * @param hexByte - byte with the desired hex value
     * @return byte in ASCII format representing the right hex digit
     */
    public static byte nibLoToASCII(byte hexByte) {
        return HEX_BYTE_MAP[hexByte & 0x0F];
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM