Java: Efficiently converting an array of longs to an array of bytes -
i have array of longs want write disk. efficient disk i/o functions take in byte arrays, example:
fileoutputstream.write(byte[] b, int offset, int length) ...so want begin converting long[] byte[] (8 bytes each long). i'm struggling find clean way this.
direct typecasting doesn't seem allowed:
conversiontest.java:6: inconvertible types found : long[] required: byte[] byte[] bytearray = (byte[]) longarray; ^ it's easy conversion iterating on array, example:
bytebuffer bytes = bytebuffer.allocate(longarray.length * (long.size/8)); for( long l: longarray ) { bytes.putlong( l ); } byte[] bytearray = bytes.array(); ...however seems far less efficient treating long[] series of bytes.
interestingly, when reading file, it's easy "cast" byte[] longs using buffers:
longbuffer longs = bytebuffer.wrap(bytearray).aslongbuffer(); ...but can't seem find functionality go opposite direction.
i understand there endian considerations when converting long byte, believe i've addressed those: i'm using buffer framework shown above, defaults big endian, regardless of native byte order.
concerning efficiency, many details will, in fact, hardly make difference. hard disk far slowest part involved here, , in time takes write single byte disk, have converted thousands or millions of bytes longs. every performance test here not tell performance of implementation, performance of hard disk. in doubt, 1 should make dedicated benchmarks comparing different conversion strategies, , comparing different writing methods, respectively.
assuming main goal functionality allows convenient conversion , not impose unnecessary overhead, i'd propose following approach:
one can create bytebuffer of sufficient size, view longbuffer, use bulk longbuffer#put(long[]) method (which takes care of endianness conversions, of necessary, , efficient can be), , finally, write original bytebuffer (which filled long values) file, using filechannel.
following idea, think method convenient , (most likely) rather efficient:
private static void bulkandchannel(string filename, long longarray[]) { bytebuffer bytes = bytebuffer.allocate(longarray.length * long.bytes); bytes.order(byteorder.nativeorder()).aslongbuffer().put(longarray); try (fileoutputstream fos = new fileoutputstream(filename)) { fos.getchannel().write(bytes); } catch (ioexception e) { e.printstacktrace(); } } (of course, 1 argue whether allocating "large" buffer best idea. convenience methods of buffer classes, , reasonable effort modified write "chunks" of data appropriate size, case 1 wants write huge array , memory overhead of creating corresponding bytebuffer prohibitively large)
Comments
Post a Comment