Last active
December 15, 2015 16:39
-
-
Save luzhuomi/5290433 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BitOp { | |
public static byte setBit(byte input, int pos) { | |
// this sets the bit of the input byte to be 1 at the position pos. | |
if (pos < 8) { | |
byte output = (byte)(input | (1 << pos)); | |
return output; | |
} | |
else { | |
return input; | |
} | |
} | |
public static byte clearBit(byte input, int pos) { | |
// this sets the bit of the input byte to be 0 at the position pos. | |
if (pos < 8) { | |
byte output = (byte)(input & ~(1 << pos)); | |
return output; | |
} | |
else { | |
return input; | |
} | |
} | |
public static int readBit(byte input, int pos) { | |
// this reads the bit value of the input byte (either 1 or 0) at the position pos. | |
if (pos < 8) { | |
byte output = (byte)(input & (1 << pos)); | |
return Byte.valueOf(output).intValue(); | |
} | |
else { | |
return -1; | |
} | |
} | |
public static byte[] setBit(byte[] input, int pos) { | |
/* | |
if (pos < 8) { | |
input[0] = setBit(input[0], pos); | |
} else if ( pos < 16 ) { | |
input[1] = setBit(input[1], pos - 8); | |
} else if ( pos < 24 ) { | |
input[2] = setBit(input[2], pos - 16); | |
} | |
*/ | |
if (pos > 63) { | |
return input; | |
} else { | |
int relPos = pos; | |
int counter = 0; | |
while (relPos >= 8) { | |
counter ++; | |
relPos = relPos - 8; | |
} | |
input[counter] = setBit(input[counter], relPos); | |
return input; | |
} | |
} | |
public static byte[] clearBit(byte[] input, int pos) { | |
if (pos > 63) { | |
return input; | |
} else { | |
int relPos = pos; | |
int counter = 0; | |
while (relPos >= 8) { | |
counter ++; | |
relPos = relPos - 8; | |
} | |
input[counter] = clearBit(input[counter], relPos); | |
return input; | |
} | |
} | |
public static int readBit(byte[] input, int pos) { | |
if (pos > 63) { | |
return -1; | |
} else { | |
int relPos = pos; | |
int counter = 0; | |
while (relPos >= 8) { | |
counter ++; | |
relPos = relPos - 8; | |
} | |
return readBit(input[counter], relPos); | |
} | |
} | |
public static byte[] int64ToByteArray(int v) { | |
// we mod v with 8. | |
// assumption: the most significant is having the larger index in the byte array | |
byte[] result = new byte[8]; | |
int quotient = v; | |
int denom = 256; // (int)Math.pow(2,8); | |
for (int i = 0; i < 8; i ++) { | |
int remainder = quotient % denom; | |
quotient = quotient / denom; | |
result[i] = (byte) remainder; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment