works
[fleet.git] / testCode / edu / berkeley / fleet / util / BitManipulations.java
1 package edu.berkeley.fleet.util;
2 import edu.berkeley.fleet.api.*;
3 import edu.berkeley.fleet.*;
4 import java.io.*;
5
6 /** useful functions for manipulating bit fields within longs */
7 public class BitManipulations {
8     public static boolean getBit(int bit, long val) { return ((val & (1L << bit)) != 0); }
9     public static long getSignedField(int highBit, int lowBit, long val) {
10         long ret = getField(highBit, lowBit, val);
11         if ((ret & (1L << ((highBit-lowBit)+1-1))) != 0)
12             ret |= 0xffffffffffffffffL << ((highBit-lowBit)+1);
13         return ret;
14     }
15     public static int getIntField(int highBit, int lowBit, long val) {
16         if (highBit-lowBit+1 > 32) throw new RuntimeException("too big!");
17         return (int)getField(highBit, lowBit, val);
18     }
19     public static long getField(int highBit, int lowBit, long val) {
20         long mask = 0xffffffffffffffffL;
21         mask = mask << ((highBit-lowBit)+1);
22         mask = ~mask;
23         mask = mask << lowBit;
24         long ret = val & mask;
25         ret = ret >> lowBit;
26         return ret;
27     }
28     public static long setField(int highBit, int lowBit, long val, long target) {
29         return (target & ~putField(highBit, lowBit, ~(-1L<<(1+highBit-lowBit)))) | putField(highBit, lowBit, val);
30     }
31     public static long doPutField(int highBit, int lowBit, long val) {
32         long mask = 0xffffffffffffffffL;
33         mask = mask << (highBit-lowBit+1);
34         mask = ~mask;
35         val = val & mask;
36         val = val << lowBit;
37         return val;
38     }
39     public static long putField(int highBit, int lowBit, long val) {
40         if (val < 0 || val >= (1L << (highBit-lowBit+1)))
41             throw new RuntimeException("bitfield width exceeded");
42         return doPutField(highBit, lowBit, val);
43     }
44     public static long putSignedField(int highBit, int lowBit, long val) {
45         if (val <= (-1L * (1L << (highBit-lowBit+1-1))))
46             throw new RuntimeException("bitfield width exceeded");
47         if (val >= (      (1L << (highBit-lowBit+1-1))))
48             throw new RuntimeException("bitfield width exceeded");
49         return doPutField(highBit, lowBit, val);
50     }
51 }