Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

int to byte[]

 
Steve Chaloner
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

not strictly a SCJD question but it's what it will be used in, so...

I want to convert an int to a byte array. I've tried using BigInteger to convert it to a binary string and from there break down the octets into bytes but that didn't work. Does anyone have another solution?

Thanks,
Steve
 
Andris Jekabsons
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this?From there this could be used/converted as needed.
 
Steve Chaloner
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Converting the int to a binary string isn't a problem - my existing code is virtually to what you suggested:



The problem comes when I convert each octet to a byte:


Testing with the int value 245 (00000000000000000000000011110101), there are no problems for the first 3 iterations. However, for the last octet I receive the following exception:

 
Andris Jekabsons
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the byte number range is -128 to +127, and 245 is out of that range.
Since I don't know what you are trying to achieve, then my best uneducated advice would be to change the logic of the program.
Andris
 
Frans Janssen
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Steve,

Assuming you need this conversion to store integers into your database file, consider looking at the RandomAccessFile's method writeInt(). It does already what you need.

See RandomAccessFile javadoc.

Good luck,

Frans.
 
Steve Chaloner
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Well, the byte number range is -128 to +127, and 245 is out of that range.


That's why the conversion results in a byte array, not a byte: 32-bit integer -> 4 8-bit bytes


Assuming you need this conversion to store integers into your database file, consider looking at the RandomAccessFile's method writeInt(). It does already what you need.


My HotelBookingRecord stores everything as byte arrays. The byte conversion was for a decorator that allowed you to interact with it using String (no problem there), booleans and integers.

I probably should rethink the strategy - but that's for later today

Thanks to you both for discussing this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic