This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bytes of junk

 
Garann Means
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'd like to create a byte array of a specified size and fill it with noise/junk characters/nonsense/whatever. I'm acting under the assumption that if I don't initialize the array, it will hold null at all positions and throw an exception as soon as I try to do anything with it. If that's true, can someone help me figure out how to fill the array?
Thanks,
g.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey there -
The good news is that arrays come 'out of the box' with default values! The integer primitives (byte short int long) come pre-loaded with 0's , the floating points w/ 0.0's, boolean arrays with false, chars w/ '\u0000' and objects with null.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say
byte[] arr = new byte[size];
(assuming "size" is an integer defined somewhere)
you initially get an array of all 0 bytes. This is perfectly valid, and you won't get any exception when you access the array elements.
But if you still really want to fill the array with random junk, take a look at Math.random(). It returns a random double between 0.0 and 1.0 (including 0.0 but not including 1.0). You'll need to multiply the result by 256 and cast it to a byte before putting it in an array element.
[ October 17, 2002: Message edited by: Ron Newman ]
 
Garann Means
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Bert and Ron.
I guess I was looking for something a little closer to C (I think it's C.. been a long time), where if you don't initialize it, you can use the random junk already already existing in the memory allocated to your new array. 0's will have to do, since I don't want to waste time giving all those bytes random values. Thanks for the suggestions, though!
g.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even in C, there's absolutely no guarantee that the contents of your uninitialized array will be random. They could well be all 0, or all 0xFF, or anything else.
You want random, you need to use a random number generator.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic