BytesConverter.java |
/* Copyright (C) 2009 CSE,IIT Bombay http://www.cse.iitb.ac.in This file is part of the ConStore open source storage facility for concept-nets. ConStore is free software and distributed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License; you can copy, distribute and transmit the work with the work attribution in the manner specified by the author or licensor. You may not use this work for commercial purposes and may not alter, transform, or build upon this work. Please refer the legal code of the license, available at http://creativecommons.org/licenses/by-nc-nd/3.0/legalcode ConStore is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package iitb.con.util; import java.util.Date; /** * ByteConverter converts primitive data type to bytes.<br> * The byte order is consider as BIG_ENDIAN * * @author Prathab K * */ public class BytesConverter { //The byte order is consider as BIG_ENDIAN /** * Returns <tt>String</tt> value as bytes * @return value as byte array */ public static byte[] getBytes(String value) { return value.getBytes(); } /** * Returns <tt>short</tt> value as bytes * @return value as byte array */ public static byte[] getBytes(short value) { byte[] bytes = new byte[2]; bytes[0] = (byte) (value >> 8); bytes[1] = (byte) value; return bytes; } /** * Returns <tt>int</tt> value as bytes * @return value as byte array */ public static byte[] getBytes(int value) { byte[] bytes = new byte[4]; bytes[0] = (byte) (value >> 24); bytes[1] = (byte) (value >> 16); bytes[2] = (byte) (value >> 8); bytes[3] = (byte) value; return bytes; } /** * Returns <tt>long</tt> value as bytes * @return value as byte array */ public static byte[] getBytes(long value) { byte[] bytes = new byte[8]; bytes[0] = (byte) (value >> 56); bytes[1] = (byte) (value >> 48); bytes[2] = (byte) (value >> 40); bytes[3] = (byte) (value >> 32); bytes[4] = (byte) (value >> 24); bytes[5] = (byte) (value >> 16); bytes[6] = (byte) (value >> 8); bytes[7] = (byte) value; return bytes; } /** * Returns <tt>float</tt> value as bytes * @return value as byte array */ public static byte[] getBytes(float value) { int i = Float.floatToIntBits(value); return getBytes(i); } /** * Returns <tt>double</tt> value as bytes * @return value as byte array */ public static byte[] getBytes(double value) { long l = Double.doubleToRawLongBits(value); return getBytes(l); } /** * Returns <tt>Date</tt> value as bytes * @return value as byte array */ public static byte[] getBytes(Date value) { return value.toString().getBytes(); } }