to Big Endian Byte Array - Java Internationalization

Java examples for Internationalization:Big Endian Little Endian

Description

to Big Endian Byte Array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int val = 2;
        byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int pos = 2;
        toBigEndianByteArray(val, b, pos);
    }/*from w  w w .  j a va  2s  .c o m*/

    public static void toBigEndianByteArray(int val, byte[] b, int pos) {
        assert (pos + 4 <= b.length);
        for (int i = 3; i >= 0; i--) {
            b[pos + i] = (byte) (val & 0x000000FF);
            val = val >> 8;
        }
    }

    public static void toBigEndianByteArray(short val, byte[] b, int pos) {
        assert (pos + 2 <= b.length);
        b[pos + 1] = (byte) (val & 0x00FF);
        b[pos] = (byte) ((val & 0xFF00) >> 8);
    }

    public static void toBigEndianByteArray(long val, byte[] b, int pos) {
        assert (pos + 8 <= b.length);
        for (int i = 7; i >= 0; i--) {
            b[pos + i] = (byte) (val & 0x00000000000000FFl);
            val = val >> 8;
        }
    }
}

Related Tutorials