scala-io read array of Ints

50 views
Skip to first unread message

marten luter

unread,
Jun 1, 2013, 12:37:17 PM6/1/13
to scala-i...@googlegroups.com
Hello, what is the best way to read Array of Ints ( not Bytes )  from binary file using scala-io?

Jesse Eichar

unread,
Jun 4, 2013, 12:51:06 AM6/4/13
to scala-i...@googlegroups.com
In what way exactly? 

There are 2 answers I can see.  

1.  THe Java input stream way where each byte is converted to an integer
2.  The "correct" way where you take 4 bytes and convert it to an integer

Both ways are supported by scala-io.

The first would be:

input.bytesAsInts.foreach(i => // do something with integer)

For the second the solution is not as neat as for writing and it should be :(  I will work on that.

// convert to a LongTraversable[Int]
val integerTraversable = for { 
    // ByteProcessor creates ints and longs in Big-Endian  but you can 
    // convert it to an implementation to parse in Little-Endian 
   processor <- ByteProcessor(input.bytes.processor) 
    // call this so you process the entire input rather than just grab
    // first integer
    _ <- processor.repeatUntilEmpty  
} yield {
  processor.nextInt
}

integerTraversable.foreach( i => // do something with integer)

As with your last email.  It is clear to me this can be improved so I am creating a ticket about the verbosity of this fairly normal case.

Jesse


On Sat, Jun 1, 2013 at 6:37 PM, marten luter <ent...@googlemail.com> wrote:
Hello, what is the best way to read Array of Ints ( not Bytes )  from binary file using scala-io?

--
 
---
You received this message because you are subscribed to the Google Groups "Scala Incubator" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-incubat...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Jesse Eichar

unread,
Jun 4, 2013, 1:01:19 AM6/4/13
to scala-i...@googlegroups.com
For the reading ints.  I forgot a simple obvious improvement  you can do the read and processing directly.

for { 
    // ByteProcessor creates ints and longs in Big-Endian  but you can 
    // convert it to an implementation to parse in Little-Endian 
   processor <- ByteProcessor(input.bytes.processor) 
    // call this so you process the entire input rather than just grab
    // first integer
    _ <- processor.repeatUntilEmpty  
}  {
  val i = processor.nextInt
// do something with int
}

In both cases there is only a single path through the data.


Probably more efficient would be to do:

input.blocks(Some(4)).foreach (block => // convert block to int and do something )

Jesse
Reply all
Reply to author
Forward
0 new messages