Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / April 2004

Tip: Looking for answers? Try searching our database.

Converting byte array to hex - not getting all characters . .

Thread view: 
Smegly - 09 Apr 2004 07:32 GMT
Hi,

I'm trying to get a text file to be converted to hexidecimal . .At present
it works .. but i do not get the entire file converted .. i can't see my
error- here is the code -

_________________________________________________________________
(from main)

public static void main(String args[])
       {

       String file = args[0];
       byte[] test = new byte[(int)file.length()];
       String str = "";
       try
       {

       test = getBytesFromFile(file);

       }
       catch (IOException e)
       {
        System.out.println("Unable to Find: " + e);
       }
       str = hexString(test);
       System.out.println(str);
       }

public static byte[] getBytesFromFile(String file) throws IOException {
       InputStream is = new FileInputStream(file);

       // Get the size of the file
       long length = file.length();

       // You cannot create an array using a long type.
       // It needs to be an int type.
       // Before converting to an int type, check
       // to ensure that file is not larger than Integer.MAX_VALUE.
       if (length > Integer.MAX_VALUE) {
           // File is too large
       }

       // Create the byte array to hold the data
       byte[] bytes = new byte[(int)length];

       // Read in the bytes
       int offset = 0;
       int numRead = 0;
       while (offset < bytes.length
              && (numRead=is.read(bytes, offset, bytes.length-offset)) >=
0) {
           offset += numRead;
       }

       // Ensure all the bytes have been read in
       if (offset < bytes.length) {
           throw new IOException("Could not completely read file "+ file);
       }

       // Close the input stream and return bytes
       is.close();
       return bytes;

   }

     public static void usage ()
   {
       System.err.println("Usage: java DEScipher filename");
   }

   /**
    * Convert a byte to a string of hexadecimal digits.
    */

   /** The hexadecimal digits "0" through "f". */
   public static char[] NIBBLE = {
                                     '0', '1', '2', '3', '4', '5', '6',
'7',
                                     '8', '9', 'a', 'b', 'c', 'd', 'e',
'f',
                                 };

   /**
    * Convert a byte array to a string of hexadecimal digits.
    */
   public static final String hexString(byte[] buf)
   {
       return hexString(buf, 0, buf.length);
   }

   /**
    * Convert a byte array to a string of hexadecimal digits.
    * The bytes <code>buf[i..i+length-1]</code> are used.
    */
   public static final String hexString(byte[] buf, int i, int length)
   {
       StringBuffer sb = new StringBuffer(length*2);
       for (int j=i; j<i+length; j++) {
           sb.append(NIBBLE[(buf[j]>>>4)&15]);
           sb.append(NIBBLE[ buf[j]     &15]);
       }
       return sb.toString();
   }

   public static final String hexString(byte a)
   {
       StringBuffer sb = new StringBuffer(2);
       sb.append(NIBBLE[(a>>>4)&0xf]);
       sb.append(NIBBLE[a&0xf]);
       return sb.toString();
   }

__________________________________________________________________

Output -

moses.cs.curtin.edu.au-70% java DEScipher message.text
54657374696e672072656164

moses.cs.curtin.edu.au-73% more message.text
Testing reading in from a file to hexidecimal

does not read all of the file ..

Any help would be appreciated . .

Matt
Roedy Green - 09 Apr 2004 08:02 GMT
see http://mindprod.com/jgloss/hex for code to go byte <-> hex.

>public static void main(String args[])
>        {
>
>        String file = args[0];
>        byte[] test = new byte[(int)file.length()];

this is unnecessary.  You replace it soon.

>        String str = "";
>        try
[quoted text clipped - 18 lines]
>
>        // You cannot create an array using a long type.
 you can't INDEX with long.  You can have an array of long.
>        // It needs to be an int type.
>        // Before converting to an int type, check
[quoted text clipped - 5 lines]
>        // Create the byte array to hold the data
>        byte[] bytes = new byte[(int)length];

you can read this with one i/o.  See
http://mindprod.com/jgloss/fileio.html for how.

>        // Read in the bytes
>        int offset = 0;
[quoted text clipped - 66 lines]
>
>Output -

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
Smegly - 09 Apr 2004 16:02 GMT
Hey Roedy,

I implemented it perfectly thanks ..

The only problem is i have too many trailing 0's .. (ie unused in the byte
array)
Is it possible to get the byte array to get as long as is needed for all the
characters in the text rounded to the next 64bit number (ie padded with 0's
at the end)

At the moment it is what you had written . .

     byte[] ba = new byte[1024];

so instead of 1024 what do i need ?? file.length() is to small ..

Matt

> see http://mindprod.com/jgloss/hex for code to go byte <-> hex.
>
[quoted text clipped - 118 lines]
> Coaching, problem solving, economical contract programming.
> See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
Roedy Green - 09 Apr 2004 19:31 GMT
>Is it possible to get the byte array to get as long as is needed for all the
>characters in the text rounded to the next 64bit number (ie padded with 0's
>at the end)

I don't see why you would want to do that. If the file was supposed to
be an even multiple of 8 bytes, then the bytes should be there to
start.

However, if what you want is to round up to the next multiple of 8,
compute the covered quotient and multiply by 8.

see http://mindprod.com/jgloss/division.html for how to compute a
covered quotient.

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.