Results 1 to 3 of 3
Thread: using Byte arrays
- 01-28-2008, 08:30 AM #1
Member
- Join Date
- Nov 2007
- Posts
- 70
- Rep Power
- 0
using Byte arrays
I was exploring byte arrays. Review the code below:
Output:Java Code:String str = "Java World for 1.4"; byte bArray[] = new byte[str.length()]; bArray = str.getBytes(); System.out.println(bArray);
So, byte arrays are not to simply keep and data in byte form and to display it. Why we use byte/byte arrays?Java Code:[B@3e25a5
Thanks in advance.
- 01-28-2008, 10:44 AM #2
One of the best example would be encoding/decoding or encryption where you need to go over the each bytes and bits .. not just storing and displaying .. Hope it helps ..
dont worry newbie, we got you covered.
- 01-30-2008, 03:54 AM #3
Member
- Join Date
- Jan 2008
- Posts
- 1
- Rep Power
- 0
Your code is all wrong.
First, you don't need:
You just need:Java Code:byte bArray[] = new byte[str.length()]; bArray = str.getBytes();
The method getBytes() creates the array and returns it. You don't need to create it yourself. What you did was create an empty array and then throw it away and replace it with the array created by getBytes.Java Code:byte bArray[] = str.getBytes();
Second, you aren't printing the array. You're printing the address in memory that the data is stored at. To print the array, you need to do the following:
(Note: I didn't actually test this code, but it should work.)Java Code:for(int iByte = 0; iByte < bArray.length; iByte++) System.print((char)bArray[iByte]); System.println();
It will print the actual characters instead of the address of the array. The system.print methods don't take arrays as arguments. They take Strings. Other objects are converted with the toString() method, but it turns out that with arrays this just outputs the address of the array.
You also have to convert the byte back into a char to avoid printing out a number instead of a character.
If you use byte arrays properly, they actually work. In that case, you'll know when you need them by the time you get to writing a real program. Roots' example is a good one.
Similar Threads
-
Byte Array
By sandor in forum New To JavaReplies: 12Last Post: 01-15-2009, 03:31 AM -
Byte Values
By javaplus in forum New To JavaReplies: 1Last Post: 06-23-2008, 12:08 AM -
BufferedImage to Byte
By Java Tip in forum Java TipReplies: 0Last Post: 01-22-2008, 08:17 PM -
int to byte
By ravian in forum New To JavaReplies: 1Last Post: 01-13-2008, 07:22 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks