Android Int to Byte Array Convert toByteArray(int val, byte[] b, int pos)

Here you can find the source of toByteArray(int val, byte[] b, int pos)

Description

to Byte Array

Declaration

public static void toByteArray(int val, byte[] b, int pos) 

Method Source Code

//package com.java2s;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;

public class Main {

    public static void toByteArray(float val, byte[] b, int pos) {
        try {//from w  w w.  java 2 s .  c  o  m
            ByteBuffer bb = ByteBuffer.allocate(4);
            FloatBuffer fb = bb.asFloatBuffer();
            fb.put(val);

            for (int i = 0; i < 4; i++) {
                b[pos + i] = bb.get(i);
            }
            // b = bb.array();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

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

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

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

Related

  1. uInt32ToBytesBI(long value, byte[] buffer, int startIndex)
  2. uInt32ToBytesLI(long value)
  3. uInt32ToBytesLI(long value, byte[] buffer, int startIndex)
  4. toByteArray(int in)
  5. toByteArray(int in, int outSize)
  6. ints2bytesBE(int[] val)
  7. ints2bytesLE(int[] val)
  8. intsToBytes(int[] values)
  9. getAs_uint16_NetOrder(int theNumber)