Friday, August 29, 2014

Type conversion of integers in Java


Let's see how integer type are converted in java internally.


Type conversion of integers in Java:

Converting from int to byte and short >>
Example>
int num=132;
byte b= (byte)num;
short s= (short) num;
------------------------------------------------------------------------------------------------------------

Explanation---
Note :>> in java byte (8-bit), short (16-bit), int (32-bit), long (64-bit) are signed 2's complement Integers,
I.e. these data types stores data in form of 2's complement, because java supports signed    integers and to store the negative values it uses the 2’s complement of their binary representation.

byte b= (byte)num;

0000 0000 0000 0000 0000 0000 1000 0100 => 32 bit int

1000 0100 => 8 bit byte [Rest of 24 bits will be chopped off to make it 8 bit from 32 bit, because 132 will not fit within the range of byte which is -128 to 127]
Here 2's complement will be taken---

0111 1011  (1s compliment)
              +1   (2s complement)
0111 1100
----------------
- 124 (byte)
----------------
*************************************************************************************
short s= (short) num;

0000 0000 1000 0100 => 16 bit short [No loss of bit so result will be same, i.e. 132, because 132 is perfectly fits within the range of short which is -32768 to 32767]
Now  Let, short s1= (short) 32769;
So,
0000 0000 0000 0000 1000 0000 0000 0001  => 32769 (an int value)

1000 0000 0000 0001  => (Rest of the bits which are out of range are chopped off here)
0111 1111 1111 1110 (1's complement)
                                  +1 (2's complement)
----------------------------
0111 1111 1111 1111 => - 32767 (short)
----------------------------


Converting from int (hex) to byte and short >>
Example>
int a=0xf1;
byte b= (byte)a;
------------------------------------------------------------------------------------------------------------

Explanation---
Note :>> in java byte (8-bit), short (16-bit), int (32-bit), long (64-bit) are signed 2's complement Integers,
I.e. these data types stores data in form of 2's complement, because java supports signed    integers and to store the negative values it uses the 2’s complement of their binary representation.

Here, int a=0xf1 , represents hexadecimal representation of int value, which is equal to 241.

So,
0000 0000 0000 0000 0000 0000 1111 0001 => 241 (an int value 32 bit)

1111 0001 => bit byte [Rest of 24 bits will be chopped off to make it 8 bit from 32 bit, because 241 will not fit within the range of byte which is -128 to 127]

0000 1110  (1’s compliment)
              +1   (2’s complement)
0000 1111
----------------
- 15 (byte)
----------------
Remember: 2’s complement will be taken when you convert the int to byte and short, or long to int.

Converting from long (hex) to int >>
Example:
long a= 0xffffffff;
int b= (int)a;
-----------------------------------------------------------------------------------------------------------

Explanation---
Note :>> in java byte (8-bit), short (16-bit), int (32-bit), long (64-bit) are signed 2's complement Integers,
I.e. these data types stores data in form of 2's complement, because java supports signed    integers and to store the negative values it uses the 2’s complement of their binary representation.
Here, long a=0xffffffff, represents hexadecimal representation of long value,which is equal to 4294967281.
So,
0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1111 >>>> 4294967281 [64 bit long]

In int>> 1111 1111 1111 1111 1111 1111 1111 1111 [Rest of the bit are chopped off to fit the digits in the range of int,which is 2-32 TO 2 31]

0000 0000 0000 0000 0000 0000 0000 0000 -- 1's complement
                                                                                +1  -- 2's complement
0000 0000 0000 0000 0000 0000 0000 0001
---------------------------------------------------------
  -1 (int)
----------------------------------------------------------

Monday, August 25, 2014

Traverse directories recursively and get the sorted URIs

Here is the utility class which can be used to traverse directories recursively and get the sorted URIs::

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Arrays;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

import java.util.TreeSet;

 

/**

* This class DirectoryTraverser.<br/>

* It returns set of files by traversing directories recursively.

*

* @since 2014

* @author Abhinav Kumar Mishra

*/

public final class DirectoryTraverser {

 

 /**

 * Gets the file URIs. Recursively traverse each directory and uris of files.

 *

 * @param aStartingDir the a starting dir

 * @return the file listing

 * @throws FileNotFoundException the file not found exception

 */

 public static Set<File> getFileUris(final File aStartingDir)

  throws FileNotFoundException {

  checkDirectories(aStartingDir); // throw exception if not valid.

  return getUrisRecursive(aStartingDir);

 }

 

 /**

 * Gets the file uris recursively.

 *

 * @param aStartingDir the a starting dir

 * @return the file listing no sort

 * @throws FileNotFoundException the file not found exception

 */

 private static Set<File> getUrisRecursive(final File aStartingDir)

  throws FileNotFoundException {

  final Set<File> sortedSetOfFiles = new TreeSet<File>();

  final File[] filesAndDirs = aStartingDir.listFiles();

  final List<File> filesDirs = Arrays.asList(filesAndDirs);

  final Iterator<File> filesDirsItr = filesDirs.iterator();

  while (filesDirsItr.hasNext()) {

   final File file = filesDirsItr.next();

   sortedSetOfFiles.add(file); // Add files and directory URIs both

   // If uri is a directory the revisit it recursively.

   if (!file.isFile()) {

    // Call 'getUrisRecursive' to extract uris from directory

    final Set<File> innerSet = getUrisRecursive(file);

    sortedSetOfFiles.addAll(innerSet);

   }

  }

  return sortedSetOfFiles;

 }

 

 /**

 * Checks if is valid directory.<br/>

 * If directory exists then it is valid. If directory is valid then it can

 * be read.

 *

 * @param directoryUri the a directory

 * @throws FileNotFoundException

  */

 private static void checkDirectories(final File directoryUri)

                            throws FileNotFoundException {

  if (directoryUri == null) {

   throw new IllegalArgumentException("Directory should not be null.");

  }if (!directoryUri.exists()) {

    throw new FileNotFoundException("Directory does not exist: "+ directoryUri);

  }if (!directoryUri.isDirectory()) {

   throw new IllegalArgumentException("Is not a directory: "+ directoryUri);

  }if (!directoryUri.canRead()) {

   throw new IllegalArgumentException("Directory cannot be read: "

                       + directoryUri);

  }

 }

 

        public static void main(String[] args) {

  try {

   System.out.println(getFileUris(new File("c:\\intel")));

  } catch (FileNotFoundException e) {

   e.printStackTrace();

  }

 }

}



Output>>
Let directory uri is: C:\Intel

Result:

[c:\intel\ExtremeGraphics,
c:\intel\ExtremeGraphics\CUI,
c:\intel\ExtremeGraphics\CUI\Resource,
c:\intel\Logs,
c:\intel\Logs\IntelChipset.log,
c:\intel\Logs\IntelGFX.log,
c:\intel\Logs\IntelGFXCoin.log]