My (mostly technical) blog

Archive for the ‘Java’ Category

I got asked this question during an interview last week. I think I gave a wrong answer in the interview but I decided I needed to find the correct answer! I searched and found this solution which involved bit manipulations, though I didn’t find it intuitive.

I came up with this simple solution

public class PowerOfTwo {
	public static void main(String args[]){
		for(int n=0,limit=16; n<Math.pow(2, limit);n++)
			if(isPowerOfTwo(n))
				System.out.println(n);
	}

	private static boolean isPowerOfTwo(int n) {
		double logNbase2 =  Math.log(n)/Math.log(2);	
		int logNbase2Integer = (int) (Math.floor(logNbase2));
		
		if(logNbase2-logNbase2Integer==0)
			return true;
		else
			return false;
	}
}
&#91;/sourcecode&#93;

maybe not quite as elegant as the bit hack, but I understand it!

<b>Update:</b>
Actually, I understood how the bit hack function below works:

	private static boolean isPowerOfTwoFast(int n) {
		return ((n!=0) && (n&(n-1))==0);
	}

Note that powers of two have only 1 bit set to one:

1:  000001
2:  000010
4:  000100
8:  001000
16: 010000
32: 100000

and so on, so we need to check if the number only has one bit that is set, and that the number is not 0 (because zero is not a power of two).

We can count the number of set bits (which is another interview question!), and if the number of set bits is one, then the number is a power of two. A smarter way to do it would be bitwise ANDing of the number and the number-1, and then check that the result == 0.

For example, to check that 32 is a power of 2, convert 32 to binary to be 100000, convert 31 to binary to be 011111. Bitwise ANDing of those 2 numbers would obviously result in 0.

Advertisements

Update: In JDK 1.6, you can get the MAC address using this method http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getHardwareAddress() 

A friend of mine ran across the problem of finding his MAC address so that he could use it in his project. Looking around the net we found a command line on Windows called “getmac”.  This command can get the MAC addresses of all the interfaces that are connected to your computer.

Below is a simple Java method that can retrieve the MAC address as a String. The only limitation is that it assumes that you only have 1 network interface (or more specifically, it will always return the MAC address of the first network interface). You could easily modify it to work for you 🙂

public static String getMac() throws java.io.IOException {
Process p = Runtime.getRuntime().exec(
“getmac /fo csv /nh”);
java.io.BufferedReader in =
new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()));
String line;
line = in.readLine();
String[] result = line.split(
“,”);
return result[0].replace(‘”‘, ‘ ‘).trim();
}

Yesterday when I was trying to send an XML document through a Socket in a Java program, I was having a lot of trouble in parsing the document when the receiver gets it. The parser was hanging. After a lot of research, I found out that the SAXBuilder.build() method needs an end of file (EOF) signal in order to finish parsing. Since I was passing the message to be parsed through an InputStream of a socket, it obviously had no EOF!

To cut a long story short, if you need to use JDOM to produce XML documents and then send them over a socket and rebuilding them at the receiver, do the following:

Sender side:
Socket serverSocket = new Socket(“localhost”, 7803);
out = new BufferedWriter(new PrintWriter(serverSocket.getOutputStream(),true));
XMLOutputter
outputter = new XMLOutputter();
outputter
.output(doc, out);

Receiver side:
ServerSocket server = new ServerSocket(7803);
Socket incoming = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream());
in.readLine(); // Skip the XML preamble (<?xml … >
String xml = in.readLine();
SAXBuilder parser =
new SAXBuilder();
Document doc = parser.build(
new StringReader(xml));
Now to make it easier on everyone, I attached the source code. Run the ServerThread first and then run the ClientMain.
http://www.pioneersawg.com/sabbour/Client.java
http://www.pioneersawg.com/sabbour/ClientMain.java
http://www.pioneersawg.com/sabbour/ServerThread.java


Ahmed Sabbour's Facebook profile
November 2017
S M T W T F S
« Jul    
 1234
567891011
12131415161718
19202122232425
2627282930  

Tweets

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

RSS StackOverflow

Recently bookmarked