Tuesday, February 13, 2007

A bug that is easily overlooked

Today I found a bug at work. The program is simple but the bug is easily overlooked. Here is the program (Java):
long timeSpan = 90 * 24 * 3600 * 1000;
System.out.println(timeSpan);
What is the result of execution?

This line is to calculate the total milliseconds of 90 days. The correct result shoudl be 7776000000, but the above program prints -813934592. We all know that it is numerical overflow. But why it is overflowed even I am already using long?

The problem is Java uses integer to store the intermediate result before assigning to the final variable. The correct syntax should be:
long timeSpan = 90L * 24 * 3600 * 1000;
System.out.println(timeSpan);

Wednesday, February 7, 2007

Preserve directory when change drive in cygwin

In cygwin, you can use "cd c:" or "cd d:" to change to different drives. However, it always change to the root directory of the drive. In Windows command prompt you have a nice feature that the c: or d: will change to the directory that you previous stayed in that drive. For example:
  
C:\Program Files\Mozilla Firefox\extensions>d:
D:\>c:
C:\Program Files\Mozilla Firefox\extensions>

However, in bash, you just can't do this
   
extensions>cd d:
d>cd c:
c>

Here I add some aliases to implement this feature in bash. Add the following lines in $HOME/.bashrc:
   
export PWD_c=c:/
export PWD_d=d:/
export PWD_e=e:/
alias c:='export PWD_`expr substr "$PWD" 11 1`="$PWD";cd "$PWD_c"'
alias d:='export PWD_`expr substr "$PWD" 11 1`="$PWD";cd "$PWD_d"'
alias e:='export PWD_`expr substr "$PWD" 11 1`="$PWD";cd "$PWD_e"'

You may need to add more PWD_x environment variables and alias in case you have more drive. Make sure you have the quotes (") because of the spaces in long file name.