Some Java Bit Functions and easy syntax hightlighting of various languages in html

Use http://tohtml.com/ and http://bedaux.net/cpp2html/ for easy syntax highlighting in your blogger posts. (I tried this with that but it doesn't seem to work).

Now the Java stuff (easily portable to C, C++ and many other languages):


    // Returs bit a to b (> a). lsb is bit 0, msb is 63, is returned as String in normal order (msb first)
    public static String getBits(long n, int a, int b) {
        String bs="";
        for (int i = a; i <= b; i++)
            bs = (1 & (n >> i)) + bs;
        return bs;
    }

    // Calculates floored log2 by finding position of highest set bit. 
    // Ignores very highest bit of long (63rd).
    public static int log2(long n) {
        long m = 1L << 62; int i = 62;
        while ((n & m) == 0 && i > 0) {m = m >> 1; i--;}
        return i;
    }

    /**
     * Extracts the n-th b-bit number. E.g. extractBitDigit(0xff00, 8, 2) =0xff. Useful for e.g. Radixsort.
     */
    public static long extractBitDigit(long value, int b, int n) {
        long m = (
                ((1 << b) - 1) // Mask
                << (n*b) // move to n-th position
                );
        return  (m &
                value) // apply
                >> (n*b) // shift down
                ;

    }

Comments

Post a Comment

Popular posts from this blog

How to monitor a directory for changes with ReadDirectoryChangesW

Coins - Pay to Win

Fastest way to zero out memory - stream past cache with movntdq/_mm_stream_si128