/** * CS 529 Sample bit-manipulation code * @author Michael Lee * Copyright (c) 2001 */ import java.io.*; public class CompressionExample { /** * sets (turns on) the pos bit in byte b */ public static byte setBit (int pos, byte b) { b |= 1 << pos; return b; } /** * unsets (turns off) the pos bit in byte b */ public static byte unsetBit (int pos, byte b) { /* not technically necessary, as byte arrays are automatically * initialized to 0's in Java --- but used as a precaution */ b &= ~( 1 << pos ); return b; } /** * compresses stuff in datain to dataout, and returns the size of the * compressed data (in bits). */ public static int compressUnary (int[] datain, byte[] dataout) { int atByte = 0, atBit = 8, bitsLeft = 0; for (int i=0; i 0) { if (atBit == 0) ++atByte; atBit = (atBit-1 >= 0)? atBit-1 : 7; dataout[atByte] = setBit(atBit, dataout[atByte]); } if (atBit == 0) ++atByte; atBit = (atBit-1 >= 0)? atBit-1 : 7; dataout[atByte] = unsetBit(atBit, dataout[atByte]); } return (atByte+1) * 8 + (8-atBit); } /** * prints out the binary makeup of a byte */ public static void printByte (byte b) { for (int i=7; i>=0; i--) { System.out.print((b >>> i) & 1); } } public static void main (String[] args) { int[] intarr = { 0, 1, 2, 3, 10 }; int complength = 0; byte[] bytearr; /* we can precalculate the amount of space needed for the * compressed array */ for (int i=0; i