readbin.javaDownload readbin.zip.
This program shows how to read a binary file produced by the
Nios II objcopy utility. This example prints hex address
and 32-bit word contents for the first few words. Note that Java
assumes a little-endian order - and we need big-endian.
// readbin.java
import java.io.*;
import java.util.Scanner;
public class readbin
{
private DataInputStream input;
private int [] b;
private int contents;
public readbin() {
b = new int[4];
}
public boolean open(String filename)
{
try {
input = new DataInputStream(
new BufferedInputStream(
new FileInputStream(filename)));
return true;
}
catch (FileNotFoundException e) {
System.err.println("Error opening file: " + filename);
return false;
}
}
public void close()
{
try {
if (input!=null) input.close();
}
catch (IOException exception)
{
}
}
public int getInt() { return contents; }
public boolean hasNext()
{
try {
// Java is exclusively little-endian, we need big-endian!
for (int i=0; i<4; i++) b[i] = (input.readByte() & 0xff);
}
catch (EOFException exception)
{
return false;
}
catch (IOException ioexception)
{
System.err.println("Error during read from file");
return false;
}
contents = (b[3]<<24)|(b[2]<<16)|(b[1]<<8)|b[0];
return true;
}
public static void main(String args[])
{
String filename;
Scanner cin = new Scanner(System.in);
if (args.length>0) filename = args[0];
else {
System.out.print("Enter file name: ");
filename = cin.nextLine();
}
int offset = 0;
if (args.length>1) offset = (int) Long.parseLong(args[1],16);
// create readbin object based on user input
readbin bin = new readbin();
if (!bin.open(filename)) return;
int address=0;
int contents;
while (bin.hasNext()) {
if (address<offset) {
address += 4;
continue;
}
contents = bin.getInt();
System.out.printf("%08x : %08x\n",address,contents);
address += 4;
// debug: shorten output file
if (address-offset>64) break;
}
bin.close();
}
}
Maintained by John Loomis, updated Sun Feb 04 21:32:54 2007