Ger Deasy
Posts: 4
Nickname: gerd
Registered: Nov, 2002
|
|
Re: Reading in Binary Numbers
|
Posted: Nov 15, 2002 4:18 AM
|
|
Heres the Program in Full, the method is reverseBits( int x )
public class BitDisplay { static void displayBits(int x){
int c, displayMask; // Create display mask displayMask = (0x1 <<15);
System.out.print(x + " = "); // Extract each of the 16 bitsfrom x one at a time. for (c = 1; c <= 16; c++){
// Determine whetherthe c'th bit from the left is a // one or a zero if ((x & displayMask)==displayMask) { System.out.print("1"); }
else { System.out.print("0"); } // Shift x left by one bit. x <<= 1;
} }
static int FirstBit( int x ) { int c, displayMask, bitPosition = 0; boolean oneFound = false;
displayMask = (0x1 << 15); c=1; while(!oneFound) { if ((x & displayMask)==displayMask) { bitPosition = c; oneFound = true; }
else { oneFound = false; } // Shift x left by one bit. x <<= 1; c++; } return bitPosition; } static int GetBits() { KeyboardInput in = new KeyboardInput(); int decimalEquivalent = 0; String binaryString; System.out.print("Please enter a binary number"); binaryString = in.readString(); int j = 0; for( int i = binaryString.length()-1; i > -1 ; i-- ) { char character = binaryString.charAt( i ); if( character == '1' ) { decimalEquivalent += (int)Math.pow(2, j); }
else { decimalEquivalent += 0; } j++; } return decimalEquivalent; }
static int reverseBits( int x ) { int displayMask, binaryReversedInt; String binaryAsString, binaryAsStringReversed;
displayMask = (0x1 <<15 );
binaryAsString = ""; binaryAsStringReversed = "";
for ( int i = 0; i <= 15; i++ ) { if((x & displayMask) == displayMask ) { binaryAsString += "1"; }
else { binaryAsString += "0"; } }
int j = 0; for ( int i = 15; i >= 0; i-- ) { char character = binaryAsString.charAt( j ); binaryAsStringReversed += character; }
binaryReversedInt = Integer.parseInt( binaryAsStringReversed ); return binaryReversedInt; }
public static void main (String[] args) { int x,c; KeyboardInput in = new KeyboardInput ();
System.out.print("Please input a decimal number:"); x = in.readInteger(); displayBits(x); System.out.print("\nPosition of Most Significant Bit " +FirstBit(x) ); System.out.println();
int binaryEquiv = GetBits(); System.out.println("Binary Equivalent is " +binaryEquiv ); System.out.println();
System.out.print( "Please enter a binary number to be reversed" ); String inputAsString = in.readString(); int input = Integer.parseInt( inputAsString, 2 ); int resultOfReverse = reverseBits( input ); System.out.println( "The result of reversing " +input+ " is " +resultOfReverse ); } }
|
|