Re: how to extend a byte[] array with a null byte?
- From: "Peter Duniho" <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Thu, 17 Apr 2008 11:09:02 -0700
On Thu, 17 Apr 2008 10:47:50 -0700, Rex Mottram <rexm@xxxxxxxx> wrote:
This should be simple but I'm struggling with it (and am somewhat of a Java newbie). I have a string
String foo = "abc";
and need to write it into a database file as a C-style string (meaning a trailing null is appended). The API takes a byte[] array, thus the current usage is something like
dbfile.add(foo.getBytes());
I simply need to take the byte[] array returned by String.getBytes() and add one extra byte containing 0 before passing it to the add() method. Try as I might I can't find the way. Help!
Huh? Just copy the bytes into a new array of the desired length, and set the last byte as needed.
For example:
String strFoo = "abc";
byte[] rgbString = strFoo.getBytes();
byte[] rgbDatabase = new byte[rgbString.length + 1];
for (int ib = 0; ib < rgbString.length; ib++)
{
rgbDatabase[ib] = rgbString[ib];
}
rgbDatabase[rgbString.length] = 0;
dbfile.add(rgbDatabase);
I was surprised to not be able to find a helper method in the Array or Arrays class that would do the copy. It's possible one exists elsewhere and I just haven't run across it yet. That would be nicer (and possibly perform better) than the for() loop above.
Also, your example (which I followed) assumes that the default character encoding is a single-byte-per-character encoding. This isn't at all necessarily going to be true. You should either standardize on a specific encoding, and explicitly provide that when you call getBytes(), or you should save information in the database describing the encoding, so that when the data is retrieved later, it can be properly interpreted.
Note also that the termination may depend on the specific encoding you're using. For example, a 16-bit encoding will expect two 0 bytes at the end, not just one.
Finally, you should be really sure that you need to save the terminating null. Presumably the database will keep track of the length of the data.. Whatever's reading the string out could theoretically just use the length of the data when encoding the bytes back to a string. Only if you're constrainted by some backwards-compatibility issue does it seem to me to bother with terminating the string with a null character.
Pete
.
- Follow-Ups:
- Re: how to extend a byte[] array with a null byte?
- From: Tom McGlynn
- Re: how to extend a byte[] array with a null byte?
- From: Rex Mottram
- Re: how to extend a byte[] array with a null byte?
- References:
- how to extend a byte[] array with a null byte?
- From: Rex Mottram
- how to extend a byte[] array with a null byte?
- Prev by Date: Re: how to extend a byte[] array with a null byte?
- Next by Date: Re: writing output to textfile
- Previous by thread: Re: how to extend a byte[] array with a null byte?
- Next by thread: Re: how to extend a byte[] array with a null byte?
- Index(es):
Relevant Pages
|