Java File Write via ByteBuffer write24BitInteger(int integer, ByteOrder order)

Here you can find the source of write24BitInteger(int integer, ByteOrder order)

Description

write Bit Integer

License

Open Source License

Declaration

public static byte[] write24BitInteger(int integer, ByteOrder order) 

Method Source Code

//package com.java2s;
/* //from  w  w  w .j  av  a  2 s  .c  o  m
 * SynaticMC
 * Copyright (C) 2016 Sander Gielisse
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.DataOutputStream;
import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public class Main {
    public static byte[] write24BitInteger(int integer, ByteOrder order) {
        ByteBuffer tmp = ByteBuffer.allocate(4);
        tmp.order(order);
        tmp.putInt(integer);

        // loose the first or last byte, we want only 3 bytes
        if (order == ByteOrder.BIG_ENDIAN) {
            return subArray(tmp.array(), 1, 4);
        } else if (order == ByteOrder.LITTLE_ENDIAN) {
            return subArray(tmp.array(), 0, 3);
        }
        throw new UnsupportedOperationException("Unknown ByteOrder " + order);
    }

    public static void write24BitInteger(int integer, ByteOrder order, DataOutputStream outputStream)
            throws IOException {
        byte[] data = write24BitInteger(integer, order);
        for (byte b : data) {
            outputStream.writeByte(b);
        }
    }

    public static byte[] subArray(byte[] array, int start, int end) {
        return Arrays.copyOfRange(array, start, end);
    }
}

Related

  1. newWriteableBuffer(int capacity)
  2. write(File file, String content, String encoding)
  3. write(InputStream source, File target)
  4. write(Path file, String content)
  5. write(SeekableByteChannel channel, long start, byte[] bytes)
  6. writeByte(WritableByteChannel channel, byte value)
  7. writeBytes(Path file, byte[] bytes)
  8. writeComment(File zipFile, String comment)
  9. writeDataLengthsToHeader(FileOutputStream fpo)