2011-05-29 116 views
3

想象一下,您將擁有數字的二進制或十六進制表示形式。讓我們藉此:Java中的按位運算子字符串

int number = 0xffffff; 
// this would recover the third f, as a stand-alone value, value of third_f would be just f 
int third_f = byteSubstring(number,2,1); 
// third and fourth f, value of tf would be ff 
int tf = byteSubstring(number,2,2); 
// all except first, value of except_first would be fffff 
int except_first = byteSubstring(number,1,5); 

使用單獨的位操作,筆&紙,我知道如何提取所有的人,但他們在一個通用功能相結合... :)。 JDK中是否有可用於數字類型的東西?

+1

其實,我不認爲你明白你非常寫什麼。 0xf是四位,二進制1111,而「第三個f」的值將是0x00f000' 0r'0x000f00',具體取決於你如何計算(你的except_first函數似乎是從1開始索引而不是0)。 – 2011-05-29 19:36:46

回答

4

您有一個sizeoffset位指定。傳統上,位從LSB開始編號。

您通過移位處理offset

result = x >>> offset 

您通過掩蔽處理的大小; (1 << size) - 1是面具

result = result & ((1 << size) - 1) 
3

Java有通常的bitwise operators,所以你可以建立一個掩碼和and你的數據。

編輯

也許一些示例代碼會多一點有用的:

// be aware - this actually substrings a hex substring, using 
// bit ops 
int byteSubString(int number, 
        int firstPos /* 0-indexed */, 
        int length) { 
     // tricky naming as hex = 2 byte per char! 
     int mask = 0; 
     switch (length) { //lookup table/array might be best here 
     case 0: mask = 0; break; 
     case 1: mask = 0xf; break; 
     case 2: mask = 0xff; break; 
     case 3: mask = 0xfff; break; 
     case 4: mask = 0xffff; break; 
     case 5: mask = 0xfffff; break; 
     default: throw new IllegalArgumentException(
       "Length of " + length + " not supported"); 
     } 
     int tmp = (number >> (4*firstPos)); 
     tmp = (tmp & mask); 
     System.out.println("Byte substring on " + 
         Integer.toHexString(number) + 
         " starting at pos " + firstPos + 
         " with length " + length + 
         " uses mask " + Integer.toHexString(mask) + 
         " results in " + Integer.toHexString(tmp)); 
     return tmp; 
    } 

當然,你也可以只呈現字符串爲十六進制表示和子串。可能會更快,更易讀:)

+0

確實。但這沒有幫助。 – Geo 2011-05-29 19:34:12

+0

爲什麼不呢?使用按位運算符編寫byteSubstring似乎並不困難。 – 2011-05-29 19:37:40

+0

@Geo添加了一些示例代碼 – extraneon 2011-05-29 20:20:25

2

Formatter「格式」語法與String.format("%x", hexa)結合。例如,String.format("%x", 0xffffff)返回String「ffffff」。然後你可以直接寫出你想要的方法作爲包裝和String.substring

但是,它無法處理二進制文件,但手動編碼更容易。

編輯:實際Integer.toBinaryString也存在。

+1

Integer.toHexString()爲你做:) – extraneon 2011-05-29 20:20:51

1

我不知道標準庫中的任何功能。 類似的東西在Integer類中,有一些函數可以對位進行一些組合操作。

您可以自己編寫它:

// offset and len are bits 
// (so you multiply them by 4 if you want to get a hex representation) 
int substring(int value, int offset, int len) { 
    value >>>= (Integer.SIZE - Integer.numberofLeadingZeros(value)) - (offset + len); 
    return value & ((1 << len) - 1); 
}