• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Writing data to a byte array.

 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
author and iconoclast
Posts: 24203
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What you really want is to use DataOutputStream together with ByteArrayOutputStream.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic