Encode a Char into Hamming Code
807569Sep 24 2006 — edited Sep 25 2006Can anyone tell me if i am on the right track of writing a java code. well i am a beginner in java and i bought this book java how to program for my self to learn how to code in java. i was just on chapter one until one of my class assignment came up to encode a character into hamming code. This is really something very advance coding. anyways if anyone would like to help i really appreciate it. if a user enters H the output should be 1001000(ASCII) and 00110010000. I am posting my code below.
class Hamming {
boolean[] a;
int n;
Hamming(boolean[] bits)
/*@Hamming_pre@*/
{
n = bits.length;
n += checkBits(n);
a = new boolean[n + 1]; /* index 0 unused */
copyBitsFrom(bits);
}
/*@Hamming_post@*/
static int checkBits(int size)
/*@checkBits_pre@*/
{
int bits = 0;
int pow = 1;
while(pow < size) {
pow *= 2;
bits++;
size++;
}
return bits;
}
/*@checkBits_post@*/
void copyBitsFrom(boolean[] bits)
/*@copyBitsFrom_pre@*/
{
int nextCheckBitPos = 1;
for(int i = 1, j = 0; i <= n; i++) {
if (i == nextCheckBitPos)
nextCheckBitPos *= 2;
else
a[i] = bits[j++];
}
}
/*@copyBitsFrom_post@*/
boolean computeBit(int k)
/*@computeBit_pre@*/
{
boolean p = false;
for(int i = k; i <= n; i+= k)
for(int j = 0; (j < k) && (i <= n); i++, j++)
p ^= a;
return p;
}
/*@computeBit_post@*/
void generateCheckBits()
/*@generateCheckBits_pre@*/
{
int n = a.length;
for(int k = 1; k < n ; k *= 2)
a[k] = computeBit(k);
}
/*@generateCheckBits_post@*/
static void demo()
/*@demo_pre@*/
{
boolean a[] = new boolean[6];
a[0] = false;
a[1] = true;
a[2] = true;
a[3] = false;
a[4] = true;
a[5] = true;
Hamming h = new Hamming(a);
h.generateCheckBits();
}
/*@demo_post@*/
static void hamming15(boolean[] a)
/*@hamming15_pre@*/
{
a[1] = a[3] ^ a[ 5] ^ a[ 7] ^ a[ 9] ^ a[11] ^ a[13] ^ a[15];
a[2] = a[3] ^ a[ 6] ^ a[ 7] ^ a[10] ^ a[11] ^ a[14] ^ a[15];
a[4] = a[5] ^ a[ 6] ^ a[ 7] ^ a[12] ^ a[13] ^ a[14] ^ a[15];
a[8] = a[9] ^ a[10] ^ a[11] ^ a[12] ^ a[13] ^ a[14] ^ a[15];
}
/*@hamming15_post@*/
static void demo15()
/*@demo15_pre@*/
{
boolean a[] = new boolean[16];
a[ 3] = false;
a[ 5] = true;
a[ 6] = true;
a[ 7] = false;
a[ 9] = true;
a[10] = false;
a[11] = false;
a[12] = false;
a[13] = false;
a[14] = false;
a[15] = false;
hamming15(a);
}
System.out.print( "\n" );
/*@demo15_post@*/
}