Java Convert via ByteBuffer toByte(char data)

Here you can find the source of toByte(char data)

Description

to Byte

License

Apache License

Declaration

public static byte[] toByte(char data) 

Method Source Code


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

import java.io.*;
import java.nio.ByteBuffer;

public class Main {

    public static byte[] toByte(char data) {
        return ByteBuffer.allocate(2).putChar(0, data).array();
    }//from  w w  w.  j av a  2 s.  c  o  m

    public static byte[] toByte(short data) {
        return ByteBuffer.allocate(2).putShort(0, data).array();
    }

    public static byte[] toByte(int data) {
        return ByteBuffer.allocate(4).putInt(0, data).array();
    }

    public static byte[] toByte(float data) {
        return ByteBuffer.allocate(4).putFloat(0, data).array();
    }

    public static byte[] toByte(long data) {
        return ByteBuffer.allocate(8).putLong(0, data).array();
    }

    public static byte[] toByte(double data) {
        return ByteBuffer.allocate(8).putDouble(0, data).array();
    }

    public static byte[] toByte(String s) {
        return s.getBytes();
    }

    public static <T extends Serializable> byte[] toByte(T data) {

        byte ret[] = null;
        try (ByteArrayOutputStream bao = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bao)) {

            oos.writeObject(data);
            bao.flush();

            ret = bao.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
}

Related

  1. toBuffer(byte[] arr)
  2. toBuffer(byte[] arr)
  3. toBuffer(int[] array)
  4. toBuffer(Serializable obj)
  5. toBuffer(String spacedHex)
  6. toByte(final char[] charArray)
  7. toByte(int input, int count)
  8. toByteArray(BitSet bits)
  9. toByteArray(char[] chars)