Bitwise Substring Operation in Java

Imagine you have a binary or hexadecimal representation of a number. Take this:

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);

Using separate bitwise operations, pen and paper, I know how to extract them all, but combining them into one common function ... :). Is there something already in the JDK that can do this for numeric types?

+3
source share
4 answers

You have sizeand offsetare indicated in bits. Traditionally, bits are numbered starting with LSB.

You process offsetby shifting the right

result = x >>> offset

You handle the size by masking; (1 << size) - 1- mask

result = result & ((1 << size) - 1)
+4
source

Java , 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;
    }

, String . :)

+3

Formatter String.format("%x", hexa). , String.format("%x", 0xffffff) String "ffffff". String.substring.

, .

: Integer.toBinaryString .

+2

I do not know any functions in the standard library that does this. Things that are the same are in the class Integer; there are some functions that perform some arranged operations on bits.

You can program it yourself:

// 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);
}
+1
source

All Articles