1 package edu.berkeley.fleet.util;
2 import edu.berkeley.fleet.api.*;
3 import edu.berkeley.fleet.*;
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);
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);
19 public static long getField(int highBit, int lowBit, long val) {
20 long mask = 0xffffffffffffffffL;
21 mask = mask << ((highBit-lowBit)+1);
23 mask = mask << lowBit;
24 long ret = val & mask;
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);
31 public static long doPutField(int highBit, int lowBit, long val) {
32 long mask = 0xffffffffffffffffL;
33 mask = mask << (highBit-lowBit+1);
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);
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);