need help

taking first bits of a binary number

Page 1 of 1

2 Replies - 716 Views - Last Post: 17 October 2007 - 01:45 PM Rate Topic: -----

#1 jack85  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 28-September 07

need help

Post icon  Posted 17 October 2007 - 01:02 PM

B) if I input 16 bits number in my binary, how can I tak e only first 8 of them.
ex: 1001010100100010
I only have to take 10010101 first 8 of them. Can someone help me with this . I need a function that can do this stuff.


this is my program :




import java.io.*;
public class BynaryFloat
{
	
	/** Creates a new instance of BynaryFloat */
	public BynaryFloat()
	{
	}
			

	public static void main(String[] args)throws IOException
	{   
	InputStreamReader reader = new InputStreamReader(System.in);
	BufferedReader input = new BufferedReader(reader);
	System.out.println("What do you want the program to do?");
	System.out.println(" Decimal to binary ... 1");
	System.out.println(" Binary to decimal ... 2");
	String choice = input.readLine();
	float c = Integer.parseInt(choice);

	if(c==1)
	{
	   System.out.println(" Enter a decimal number:");
	   String dba=input.readLine();
		   int db = Integer.parseInt(dba);
	   System.out.println(db);
	   int [] m = new int [10];
	   int j, A;
		   for(j=8;j>=1;j--)
		   {
				  m[j] = db%2;
			  db = db/2;
		   }
				int sc = 0;
			  
				  for(j=1;j<=8;j++)
			{
			   if(m[j]==0)
				 {
							   if(sc==0)
									{
									   continue;
									}
				 }
							 System.out.print(+m[j] + " ");
							 sc = sc+1;
					   }				  
	}

   if(c==2)
   {
	  System.out.println("Enter a binary number");
	  String bda=input.readLine();
	  float l=bda.length()-1;
	  double sum =0;
	   for(int w =0;w<bda.length();w++)
	   {
			  char r = bda.charAt(w);
			  String str = new Character®.toString();
		  float er = Integer.parseInt(str);
		  sum = sum + (er*Math.pow(2,l));
			  l--;
			  
   	   }
			   
	   System.out.println("The decimal is : "+sum);
   }

   
}
	
}


Is This A Good Question/Topic? 0
  • +

Replies To: need help

#2 skyhawk133  Icon User is offline

  • Head DIC Head
  • member icon

Reputation: 1876
  • View blog
  • Posts: 20,284
  • Joined: 17-March 01

Re: need help

Posted 17 October 2007 - 01:16 PM

Please put your code in between [ code ] tags like the instructions say.
Was This Post Helpful? 0
  • +
  • -

#3 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: need help

Posted 17 October 2007 - 01:45 PM

before converting to a number, simply use the String.substring function, or if it is already a number, divide it by 2^8 which is the same thing as using the >>operator and shifting it 8 bits to the left.
and please don't post the same question in multiple threads, thank you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1