to Big Endian Integer - Java Internationalization

Java examples for Internationalization:Charset

Description

to Big Endian Integer

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int pos = 2;
        System.out.println(toBigEndianInteger(b, pos));
    }/*from  w  ww  . j  a v a 2  s .com*/

    public static int toBigEndianInteger(byte[] b, int pos) {
        int ret = 0;
        for (int i = 0; i < 4; i++) {
            ret |= (b[i + pos] & 0xFF) << (8 * (3 - i));
        }
        return ret;
    }

    public static int toBigEndianInteger(byte[] b, int pos, int width) {
        int retVal = Integer.MAX_VALUE;
        switch (width) {
        case 1:
            retVal = b[pos];
            if (retVal < 0) {
                retVal &= 0x000000FF;
            }
            break;
        case 2:
            retVal = toBigEndianIntFromTwoBytes(b, pos);
            break;
        case 4:
            retVal = toBigEndianInteger(b, pos);
            break;
        default:
            break;
        }

        return retVal;
    }

    public static int toBigEndianIntFromTwoBytes(byte[] b, int pos) {
        int ret = 0;
        ret |= (b[pos + 1] & 0xFF);
        ret |= (b[pos] & 0xFF) << 8;

        return (int) ret;
    }
}

Related Tutorials