byte encrypted [] = new byte [8] ;
int encryptedInt [] = new int [] = {
1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,0,1,1,
0,1,0,1,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,0,1,01,0,1,1,0,1,0,0,
0,0,0,0,0,1,0,1 };
// convert encryptedInt back to binary
int pack [] = new int [8] ;
for (i = 0; i < 8; i++) { //each individual byte
for (int j = 0; j < 8; j++) { // each bit in that byte
pack [j] = encryptedInt [j+(8*i)] ;
}
encrypted [i] = packByte (pack) ;
}
private byte packByte (int [] toPack) {
int byteVal = 0 ;
int temp = 0 ;
int i ;
byteVal = toPack[0] & 0x1 ;
byteVal <<= 7 ;
for (i = 7; i > 0; i--) {
temp = toPack [8 - i] & 0x1 ;
//System.out.print ("Bit " + (8 - i) + " " + temp + " ") ;
temp <<= i - 1 ;
//System.out.println (temp) ;
byteVal = byteVal | temp ;
byteVal = byteVal & 0xff ;
//System.out.println (byteVal) ;
}
// byteval has the value of the byte
return (byte) byteVal ;
}
Thomas Schodt - 03 Oct 2005 19:57 GMT
> byte encrypted [] = new byte [8] ;
You did not include the code where you print this...
djbitchpimp@snowboard.com - 03 Oct 2005 21:02 GMT
byteArrToString(encrypted) ;
/* prints out the binary representation of a byte array */
public static void byteArrToString (byte [] toPrint) {
for (int i = 0; i < toPrint.length; i++) {
printBinary(toPrint [i]) ;
}
//System.out.println () ;
}
// Takes an int as an argument and prints it in binary.
// Returns the length of the number in binary.
// if boolean is false, it won't print anything.
public static void printBinary(byte value) {
boolean shouldPrint = true;
int hasPrinted = 0;
int pos = 32;
while (pos > 0) {
if (checkBit(value, pos)) {
System.out.print(shouldPrint ? "1" : "");
hasPrinted++;
} else if (hasPrinted > 0) {
System.out.print(shouldPrint ? "0" : "");
hasPrinted++;
}
pos--;
}
System.out.print(shouldPrint ? " " : "");
//return hasPrinted;
}
Steve Horsley - 03 Oct 2005 22:40 GMT
> byteArrToString(encrypted) ;
>
[quoted text clipped - 28 lines]
> //return hasPrinted;
> }
You don't post the code for checkBit(byte), but I guess that your
problem is actually this line:
int pos = 32;
This explicitly asks to print bit values from position 32
downwards. Starting with pos=8 shoudl fix it.
You seem not to know about promotion and sign extension. Almost
any operation on a byte (including bitwise operations) first
promotes the byte to an int value and then performs the
operation. As part of that promotion, a negative byte (e.g. -1 =
11111111) has the extra ones added to keep the same value as an
int (-1 = 11111111111111111111111111111111).
HTH
Steve