簡體   English   中英

如何從組合布爾值中獲取十六進制值?

[英]How to get hexadecimal value from combined booleans?

我想從四個布爾變量中獲取一個十六進制值,如下例所示:

boolean[] m = {true, false, true, true};

我想得到一個包含B的字符串或字符,這意味着二進制1011

PS:我正在開發一個 Android 應用程序。

您可以使用下面的代碼來獲取您的二進制字符串、整數值和 hexDecimal 值。

    boolean[] m = {true,false,true,true};
    String binaryStr = "";
    for (boolean bit : m) {
        binaryStr = binaryStr + ((bit) ? "1" : "0" );
    }
    int decimal = Integer.parseInt(binaryStr , 2);
    String hexStr = Integer.toString(decimal , 16);

在上面的代碼中, binaryStr是您的二進制字符串,即1011 ,其等效的十進制和十六進制十進制值是decimalhexStr

boolean[] booleanArray = new boolean[] { true, false, false, true };
String binaryString = Arrays.toString(booleanArray).replace("true", "1").replace("false", "0");

只需將該 binaryString 轉換為十六進制值

雖然上述答案確實有效,但它們有其局限性。 由於 32 位整數限制,第一個限制是 32 個布爾值。 但是上面的代碼也使用了內置方法,它們不允許初學者掌握真正發生的事情。

如果您只是想完成工作,請使用上面的內容。 它可能會更有效率。 我只是發布這個解決方案,因為我覺得它會讓想要掌握實際概念的人做得更好。

(希望評論有點道理)

public static String booleanArrayToHex1(boolean[] arr){

    if(!(arr.length%4==0)){arr=makeMultOf4(arr);} //If you are using arrays not in multiples of four, you can put a method here to add the correct number of zeros to he front.
    //Remove the above line if your array will always have a length that is a multiple of 4

    byte[] hexValues=new byte[arr.length/4]; 
    //The array above is where the decimal hex values are stored, it is byte because the range we need is 0-16, bytes are the closest to that with the range of 0-255

    int hexCounter=arr.length/4-1; //counts what hex number you are calculating

    /* The below loop calculates chunks of 4 bianary numbers to it's hex value
     * this works because 16 is a power of 2
     * so if we simpily squish those numbers together it will be the same as finding the accual integer value of the whole thing
     * This can go to higher numbers because we do not have the 32 bit integer limit
     * it runs in reverse because the lowest value is on the right of the array (the ones place is on the right)
     */
    for(int i=arr.length-1;i>=0;i--){
        if(arr[i]){
            int place=1; //will count the value of a bianary number in terms of its place

            for(int j=3;j>i%4;j--) 
            //loop multiplies the bianary number by 2 j times, j being what place it's in (two's, four's, eight's). This gives the correct value for the number within the chunk.
            //This is why the array needs to be a multiple of 4
                place*=2;

            hexValues[hexCounter]+=place; //this will add that place value to the current chunk, only if this place in the boolean array is true (because of the above if - statement)
        }

        if(i%4==0)//moves the chunk over one every 4 binary values
            hexCounter--;
    }

    //Everything below simpily takes the array of decimal hex values, and converts to a alpha-numeric string (array to normal hex numbers)
    String ret="";
    for(byte b:hexValues)
        switch(b){
            case 10:
            ret=ret+"A";
            break;
            case 11:
            ret=ret+"B";
            break;
            case 12:
            ret=ret+"C";
            break;
            case 13:
            ret=ret+"D";
            break;
            case 14:
            ret=ret+"E";
            break;
            case 15:
            ret=ret+"F";
            break;
            default:
            ret=ret+b;
            break;
        }
    return ret;
}

如果您的數組長度不是 4 的倍數,要完成這項工作,您需要將數組設為 4 的倍數。我在下面有一些代碼可以做到這一點。 它沒有評論,可能效率不高,但它有效。

public static boolean[] makeMultOf4(boolean[] arr){
    if(arr.length%4==0){return arr;}
    boolean[] array=new boolean[arr.length+(arr.length%4==1?3:arr.length%4==2?2:1)];
    for(int i=0;i<array.length;i++){
        try{
            array[i]=arr[i-(arr.length%4==1?3:arr.length%4==2?2:1)];
        }catch(Exception e){
            array[i]=false;
        }
    }
    return array;
}

您可以使用此邏輯:

String x = ""; 
for(int i  = 0 ; i < m.length ; i++){
    if(m[i])
      x += "1";
    else
       x += "0";
 }

Log.i("values = ",x);

對於每個布爾值附加到binary字符串 1 如果true 0 否則,然后使用Integer.parseInt()將二進制字符串轉換為 Integer 實例,最后使用Integer.toHexString()方法將整數轉換為十六進制字符串

@org.junit.Test
public void test() throws Exception{

    boolean[] m = {true, false, true, true};
    String binary = "";

    for(boolean b : m) binary += b ? 1 : 0;

    String hex = Integer.toHexString(Integer.parseInt(binary, 2));

    System.out.println(hex);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM