• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing data to a byte array.  RSS feed

 
Sarone Thach
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey there,
Can anyone tell me how i can write data to a byte array.
For example I would like to add a char to a byte array. The compiler complains about my code below. Why?

I would like to copy the contents of a string to the array. Does the below make sense?


I would like to copy an int. Would the below code actually work? If not what is the best way?

Any help would be great. Thanks for you time.
Sarone
[ December 02, 2003: Message edited by: Sarone Thach ]
 
Susilo Saja
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sarone,
I found 2 main mistakes in your code:
- Incompatible data types
- Passing non-array as argument to System.arrayCopy
This is the correct version of your first example:
char c = 'd';
byte[] bArray = new byte[5];
bArray[0] = (byte)c;
If you wish to use System.arrayCopy:
System.arraycopy(new byte[] {(byte)c}, 0, bArray, 0, 1);
You can find a more complete explanation in the api doc of System.arrayCopy
 
Igor Ko
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See also java.io.ByteArrayOutputStream.

If you wish to save char into byte array, you should think about
order to save, because char are two bytes. So what byte will be
the first ?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you really want is to use DataOutputStream together with ByteArrayOutputStream.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!