001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.imaging.common; 018 019import java.io.IOException; 020import java.io.PrintWriter; 021import java.io.StringWriter; 022import java.nio.ByteOrder; 023import java.util.logging.Level; 024import java.util.logging.Logger; 025 026public class BinaryFileParser { 027 028 private static final Logger LOGGER = Logger.getLogger(BinaryFileParser.class.getName()); 029 030 // default byte order for Java, many file formats. 031 private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; 032 033 public BinaryFileParser(final ByteOrder byteOrder) { 034 this.byteOrder = byteOrder; 035 } 036 037 /** 038 * Constructs a BinaryFileParser with the default, big-endian, byte order. 039 */ 040 public BinaryFileParser() { 041 // as above 042 } 043 044 protected void setByteOrder(final ByteOrder byteOrder) { 045 this.byteOrder = byteOrder; 046 } 047 048 public ByteOrder getByteOrder() { 049 return byteOrder; 050 } 051 052 protected final void debugNumber(final String msg, final int data, final int bytes) { 053 try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { 054 debugNumber(pw, msg, data, bytes); 055 pw.flush(); 056 sw.flush(); 057 LOGGER.fine(sw.toString()); 058 } catch (final IOException e) { 059 LOGGER.log(Level.SEVERE, e.getMessage(), e); 060 } 061 } 062 063 protected final void debugNumber(final PrintWriter pw, final String msg, final int data, final int bytes) { 064 pw.print(msg + ": " + data + " ("); 065 int byteData = data; 066 for (int i = 0; i < bytes; i++) { 067 if (i > 0) { 068 pw.print(","); 069 } 070 final int singleByte = 0xff & byteData; 071 pw.print((char) singleByte + " [" + singleByte + "]"); 072 byteData >>= 8; 073 } 074 pw.println(") [0x" + Integer.toHexString(data) + ", " + Integer.toBinaryString(data) + "]"); 075 pw.flush(); 076 } 077}