• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting byte array to long

 
David Coppens
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a problem with my assignment.

I am trying to read the 2 bytes that identify the number of fields
in each record.

This is stored in a byte array b.
In debug mode the following is present:
b[0] = ""
b[1] = "7"

I want to convert this to a long or integer.
But if I do this:
new String(b, "UTF-8") I end up with two blocks: "[][]"
And ofcourse I cannot convert this further to a Long.

How should I go about doing this?

Kind regards,
David
 
Alex Belisle Turcot
Ranch Hand
Posts: 516
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I would think it's a bit odd the field you read starts with an 'null' character...



Maybe I went completely off track with my sample, please tell me if that's the case. However, I believe if you hope to find a number there, I would think you are 1 offset off.

Regards,
Alex
[ November 30, 2007: Message edited by: Alex Belisle Turcot ]
 
Musab Al-Rawi
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

How about reading that number of fields as a short.
RandomAccessFile class has a list of easy useful methods such as readShort().

Hope that helps
 
Alex Belisle Turcot
Ranch Hand
Posts: 516
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Musab's reply makes a lot more sense, you could read directly the type/size you're looking for and not worry about the conversion..

The offset thing I mentioned might be completely wrong actually, if you just read the correct type, it will get converted correctly.



Regards,
Alex
 
David Coppens
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
readShort does indeed do the job.
However, I was trying to make my file reader class as dynamic as possible, thus I have a constant that identifies the number of bytes that are used to store the 'number of fields per record'.

In this case I know it is 2 bytes, but it could change to 1 or 4 in which case readShort would not be the right choice.

But for the sake of simplicity I think I will just make the file reader a little less dynamic. It's not a requirement, so I should be safe.

Thanks for your help!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic