Java Integer Convert To convertInttoMultiByte(int val)

Here you can find the source of convertInttoMultiByte(int val)

Description

Works for positive values only

License

Apache License

Parameter

Parameter Description
val a parameter

Declaration

public static int[] convertInttoMultiByte(int val) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from   ww w  .j  av  a 2s .  c  o m*/
     * Works for positive values only
     *
     * @param val
     * @return
     */
    public static int[] convertInttoMultiByte(int val) {

        if (val < 0) {
            throw new IllegalArgumentException("Negative values are not supported");
        }

        // must decompose into a max of 4 bytes
        // b1      b2       b3        b4
        // 01111111 11111111 11111111 11111111
        // 127      255      255      255

        int size = 0;

        if ((val >> 24) > 0) {
            size = 4;
        } else if ((val >> 16) > 0) {
            size = 3;
        } else if ((val >> 8) > 0) {
            size = 2;
        } else {
            size = 1;
        }

        int[] data = new int[size];

        for (int i = 0; i < size; i++) {
            data[i] = (val >> (size - i - 1) * 8) & 0xFF;
        }

        return data;
    }
}

Related

  1. convertIntoRange(Integer inValue, int inSteps, int inMin, int inMax)
  2. convertIntToDayOfWeek(int day)
  3. convertIntToDouble(final int[] intValues)
  4. convertIntToDWord(final int value)
  5. convertIntToLong(Integer intId)
  6. convertIntToTwoChar(int n)
  7. convertIntToUsignedBytes(int integer)
  8. fromInt(byte[] buffer, int pos, int i)
  9. fromInt(final int value, final int length)