Sunday 19 July 2009

BUG, HOWTO: how java read 8-bit and 16-bit

you have to use twice as much memory, but there really is no other solution:
=======================

use a short to hold an unsigned byte, use a long to hold an unsigned int. (And use a char to hold an unsigned short.)

This example create a 16-bit file, which only contain a value, 15 in 16-bit (000f), This file can be viewed by Gedit. From Matlab, it can retrieve and display correctly as 15, but in Java, using DataInputStream.readShort(), it's 3840, which equals to 15*256.



Example 1: Using Matlab to generate a 16-bit data file.
================
clear;clc;%% create binA=15;fid = fopen('output.bin', 'w'); fwrite(fid, A, 'uint16');fclose(fid);%% read binfid1 = fopen('output.bin', 'r'); B = fread(fid1, 1, 'uint16')fclose(fid1);

Example 2: Using Java to retrive the 16-bit data from the bin file.
===========
import java.io.*;public class convbin { public static void main(String args[]) throws IOException { File file = new File("onev.bin"); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream( bis );// RandomAccessFile dis = new RandomAccessFile(new File("fotech1.bin"), "r"); short[] myarray = new short[256000]; int cnt; for (cnt = 0; cnt < 1; cnt++) { myarray[cnt] = dis.readShort(); } fis.close(); System.out.println("Done."); FileOutputStream fos = new FileOutputStream(new File("o22.bin")); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos);// RandomAccessFile dos = new RandomAccessFile(new File("o22.bin"), "rw"); for (cnt = 0; cnt < 1; cnt++) { dos.writeShort(myarray[cnt]); } System.out.println("Finish."); bos.flush(); fos.close(); }}

More details, except the example: http://www.darksleep.com/player/JavaAndUnsignedTypes.html

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter