scala - Reading from InputStream as an Iterator[Byte] or Array[Byte] -
i representing data object iterator[byte], created inputstream instance.
the problem lies in byte signed integer -128 127, while read method in inputstream returns unsigned integer 0 255. in particular problematic since semantics -1 should denote end of input stream.
what best way alleviate incompatibility between these 2 types? there elegant way of converting between 1 another? or should use int instead of bytes, though feels less elegant?
def tobyteiterator(in: inputstream): iterator[byte] = { iterator.continually(in.read).takewhile(-1 !=).map { elem => convert // need convert unsigned int byte here } } def toinputstream(_it: iterator[byte]): inputstream = { new inputstream { val (it, _) = _it.duplicate override def read(): int = { if (it.hasnext) it.next() // need convert byte unsigned int else -1 } } }
yes, can convert byte int , vice versa easily.
first, int byte can converted tobyte:
scala> 128.tobyte res0: byte = -128 scala> 129.tobyte res1: byte = -127 scala> 255.tobyte res2: byte = -1 so elem => convert _.tobyte.
second, signed byte can converted unsigned int handy function in java.lang.byte, called tounsignedint:
scala> java.lang.byte.tounsignedint(-1) res1: int = 255 scala> java.lang.byte.tounsignedint(-127) res2: int = 129 scala> java.lang.byte.tounsignedint(-128) res3: int = 128 so can write java.lang.byte.tounsignedint(it.next()) in second piece of code.
however, last method available since java 8. don't know alternatives in older versions of java, actual implementation astonishingly simple:
public static int tounsignedint(byte x) { return ((int) x) & 0xff; } so need write
it.next().toint & 0xff
Comments
Post a Comment