Showing posts with label Binary. Show all posts
Showing posts with label Binary. Show all posts

Monday, April 10, 2017

java and SQL: Check if a binary number contains certain value

Below are some examples of binary numbers

Decimal format                   Binary format
2                                        00000010
16                                      00010000
18                                      00010010


In Java the operation to test if a binary number contains certain value is "&". For example,

             if ((theNumber & 4) == 4) {
                     . . . . . .
             }

             System.out.println((16 & 2) == 2);  The output is false;
             System.out.println((18 & 2) == 2); The output is true;

In SQL the operation to test if a binary number contains certain value is "bitand". For example,

             select * from Fruit where (bitand (criteria, 8) = 8);
---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, April 15, 2014

CLOBs, NCLOBs and BLOBs

CLOB, NCLOB and BLOB are database data types with data size up to 128 terabytes. The data size of regular VARCHAR and VARBINARY is 32 kilobytes.

CLOB stands for character large object, which is a Unicode character string. It is appropriate for storing text-orientated information.

NCLOB stands for national character large object, which is a Unicode character string. This data type like the CLOB data type, is appropriate for storing text-orientated information.

BLOB stands for binary large object, which is a binary string. This data type is appropriate for storing images, sound, and videos.

Following is a sample code of using these data types.

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;

public class Test {
      public static void main(String[] args) {
            Connection conn = null;
            try {
                  conn = <your method of getting the database connection>;
         

               //Save data to database

                  //Create the data type objects
                  Clob theClob = conn.createClob();
                  NClob theNclob = conn.createNClob();
                  Blob theBlob = conn.createBlob();
         
                  //Add data to the data type objects
                  BufferedReader charReader = new BufferedReader(
                           new FileReader("descritpion.txt"));
                  StringBuilder file = new StringBuilder();
                  String line = "";
                  while ((line = charReader.readLine()) != null){
                         file.append(line);
                  }
         
                  theClob.setString(1, file.toString());
                  theNclob.setString(1, file.toString());
                  charReader.close();
         
                 BufferedInputStream input = new BufferedInputStream(
                          new FileInputStream("happyBird.gif"));
         
                 OutputStream byteWriter = theBlob.setBinaryStream(1);
                  int theChar = -1;
                  while ((theChar = input.read()) != -1) {
                        byteWriter.write(theChar);
                  }
                  byteWriter.flush();
                  input.close();
                  byteWriter.close();
         
                  //Insert the data into database
                  String sql = "INSERT into picture values(?, ?, ?)";
                  PreparedStatement pstmt = conn.prepareStatement(sql);
                  pstmt.setClob(1, theClob);
                  pstmt.setNClob(2, theNclob);
                  pstmt.setBlob(3, theBlob);
                  pstmt.executeUpdate();
                  pstmt.close();

              //Retrieve data from database

                  String sql2 = "SELECT title, description, image from picture";
                  pstmt = conn.prepareStatement(sql2);
                  ResultSet rs = pstmt.executeQuery();
                  while (rs.next()) {
                         Clob myClob = rs.getClob(1);
                         String title = myClob.getSubstring(1, myClob.length());

                         NClob myNclob = rs.getNClob(2);
                         String description = myNclob.getSubstring(1, myNclob.length());

                         Blob myBlob = rs.getBlob(3);
                         byte[] imageArray = myBlob.getBytes(1, myBlob.length());
                  }
                   rs.close();
                   pstmt.close();
                  conn.close();
            }catch (Exception e){
                  e.printStackTrace();
            }
      }
}

References:

1.Using Large Objects
2. 26 Oracle Data Types

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, February 27, 2014

Java how to read a binary file prepared by a c program

A. The bits of the primitives are different in c and in Java.


Java:
       byte:              8 bits/1 byte
       short/char:     16 bits/2 bytes
       int/float:         32 bits/4 bytes
       long/double:   64 bits/8 bytes

c:
       char:              8 bits/1 byte
       short:             16 bits/2 bytes
       int/long/float:  32 bits/4 bytes
       double:          64 bits/8 bytes

B. The byte order in Unix and Windows are different. In general Unix uses the big endian and windows uses the little endian.

     

C. If a binary file is prepared by a c program and you are reading it in a java program, you need to adjust the read method to ensure that you read the right amount of bytes of that data type in c. If the binary file is prepared on a Unix machine and is read in a Windows system or vise versa, you need to adjust the byte order accordingly.


       File theFile = new File("<fileName>");
       FileInputStream fis = new FileInputStream(theFile);
       byte[] byteArray = new byte[(int)theFile.length()];
       fis.read(byteArray);
       ByteBuffer buffer = ByteBuffer.wrap(byteArray);


       //Add the following line if the binary file is prepared on a Unix machine and read on a Windows machine
       buffer.order(ByteOrder.LITTLE_ENDIAN);
       //Add this line if it is prepared on a Windows system and read on a Unix machine
       buffer.order(ByteOrder.BIG_ENDIAN);

 To read a char, instead of using buffer.getChar() which reads two bytes in java, you need to use (char)buffer.get(). 

To read a long, instead of using buffer.getLong() which reads 8 bytes in java, you need to use (new Integer(buffer.readInt())).longValue().

References:
2. How to convert byte array or char array to string in Java

----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Java read from and write to a binary stream

A. Write to a binary stream

Assume that you have the following data that you would like to write to a binary stream.
      char aChar = 'T';
      long aLong = 109876L;
      int aInt = 98;
      String aString = "Nice"; //4 chars

1. Create the ByteBuffer
In java, char is 2 bytes, long is 8 bytes, int is 4 bytes. For the above data, we need in total 22 bytes.

      ByteBuffer buffer = ByteBuffer.allocate(22);

2. Put the data to the ByteBuffer
      buffer.putChar(aChar);
      buffer.putLong(aLong);
      buffer.putInt(aInt);
      buffer.put(aString.getBytes());

3. Write to the OutputStream
The code here is an example of how to write to a FileOutputStream.

      FileOutputStream fos = new FileOutputStream("<fileName>");
      fos.write(buffer.array());

B. Read from a binary stream

The sample code shows how to read from the binary file created above.

1. Create/get the InputStream
      File theFile = new File("<fileName>");
      FileInputStream fis = new FileInputStream(theFile);

2. Read data into a byte array
      byte[] byteArray = new byte[(int)theFile.length()];
      fis.read(byteArray);

3. Get the data
      ByteBuffer buffer = ByteBuffer.wrap(byteArray);
      char aChar = buffer.getChar();
      long aLong = buffer.getLong();
      int aInt = buffer.getInt();
      String aString = "";
      for (int i=0; i<4; i++) {
            sString += buffer.getChar();
      }

References:
1. How to convert byte array or char array to string in Java
2. Java how to read a binary file prepared by a c program

------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.