1

The java project i am working on requires me to write the java equivalent of this C code:

void read_hex_char(char *filename, unsigned char *image)
{
    int     i;
    FILE   *ff;
    short  tmp_short;
    ff = fopen(filename, "r");
    for (i = 0; i < 100; i++)
    {
        fscanf(ff, "%hx", &tmp_short);
        image[i] = tmp_short;
    }
    fclose(ff);
}

I have written this Java code.

void read_hex_char(String filename, char[] image) throws IOException
{
    Scanner s=new Scanner(new BufferedReader(new FileReader(filename)));
    for(int i=0;i<100;i++)
    {
        image[i]=s.nextShort();
    }
    s.close();
 }

Is this code correct? If its not, what corrections should be done?

Rog Matthews
  • 3,147
  • 16
  • 37
  • 56

3 Answers3

1

I would go with a FileInputStream and read byte to byte (a short is just two bytes, char is more "complex" than just a short http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). Simple byte extraction code from my project :

public static byte[] readFile(File file) throws IOException {
    FileInputStream in = new FileInputStream(file);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int ch = -1;
    while ((ch = in.read()) != -1)
        bos.write(ch);
    return bos.toByteArray();
}

For your example, the simplest is to find a few samples : run the C function on it then the java one and compare the results. It should give you informations.

Vinze
  • 2,549
  • 3
  • 22
  • 23
0

Keep in mind, that java char type is pretty smart (smarter than just byte) and represents unicode character ( and reader classes perform processing of incoming byte stream into unicode characters possibly decoding or modifyiung bytes according to actual locale and charset settings ). From your source I guess that it is just actual bytes you want in memory buffer. Here is really good explanation how to do this:

Convert InputStream to byte array in Java

Community
  • 1
  • 1
Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
0

For parsing hex values, you can use Short.parseShort(String s,int radix) with radix 16. In Java, char is a bit different than short, so if you intend to perform bitmap operations, short is probably the better type to use. However, note that Java doesn't have unsigned types, which may make some of the operations likely to be used in image processing (like bitwise operations) tricky.

Michał Kosmulski
  • 9,855
  • 1
  • 32
  • 51