Java/Data Type/Data Type cast
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A simple casting demo
- 2 Cast a float or double to an integral value
- 3 Casting Demo
- 4 Class with methods for type conversion
- 5 Conversion utilities
- 6 Convert Byte array to Int
- 7 Convert byte array to Long
- 8 Convert long to Bytes
- 9 Convert Number To Target Class
- 10 Data type conversion
- 11 Data type Conversion Util
- 12 Get the minimum and maximum value of a primitive data types?
A simple casting demo
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
/** A simple casting demo. */
public class CastingDemo {
public static void main(String[] argv) {
int i, ans;
double d = 2.75;
i = d; // EXPECT COMPILE ERROR
i = (int)d; // with cast; i gets 2
System.out.println("i =" + i);
ans = (int)d * 3; // truncate d before multiplying
System.out.println("ans =" + ans);
ans = (int)(d * 3); // multiplies before truncating
System.out.println("ans =" + ans);
}
}
Cast a float or double to an integral value
//: c03:CastingNumbers.java
// What happens when you cast a float or double to an integral value?
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class CastingNumbers {
public static void main(String[] args) {
double above = 0.7, below = 0.4;
System.out.println("above: " + above);
System.out.println("below: " + below);
System.out.println("(int)above: " + (int)above);
System.out.println("(int)below: " + (int)below);
System.out.println("(char)("a" + above): " + (char)("a" + above));
System.out.println("(char)("a" + below): " + (char)("a" + below));
}
} ///:~
Casting Demo
/** Casting Demo. */
public class CastNeeded {
//+
public static void main(String[] argv) {
int i;
double j = 2.75;
i = j; // EXPECT COMPILE ERROR
i = (int)j; // with cast; i gets 2
System.out.println("i =" + i);
byte b;
b = i; // EXPECT COMPILE ERROR
b = (byte)i; // with cast, i gets 2
System.out.println("b =" + b);
}
//-
}
Class with methods for type conversion
/**********************************************************************
Copyright (c) 2004 Brendan de Beer and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
2004 Brendan de Beer - Initial contributor for conversion methods
2005 Erik Bengtson - refactor mapping
2005 Andy Jefferson - added Timestamp/String converters
...
**********************************************************************/
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
/**
* Class with methods for type conversion
*
* @version $Revision: 1.19 $
*/
public class TypeConversionHelper
{
private static int NR_BIGINTEGER_BYTES = 40; //not sure how big we need the array to be, so use 40
private static int NR_SCALE_BYTES = 4;
private static int NR_SIGNAL_BYTES = 1;
private static int TOTAL_BYTES = NR_BIGINTEGER_BYTES+NR_SCALE_BYTES+NR_SIGNAL_BYTES;
/**
* Convert an instance of our value class into a boolean[].
*
* @param value Object to be converted
*
* @return converted boolean array
*/
public static boolean[] getBooleanArrayFromBitSet(BitSet value)
{
if (value == null)
{
return null;
}
boolean[] a = new boolean[value.length()];
for( int i=0; i<a.length; i++)
{
a[i] = value.get(i);
}
return a;
}
/**
* Convert a boolean[] into an instance of our value class.
*
* @param buf boolean array to be converted
*
* @return converted boolean array as BitSet
*/
public static BitSet getBitSetFromBooleanArray(boolean[] buf)
{
BitSet set = new BitSet();
for (int i = 0; i < buf.length; i++)
{
if( buf[i] )
{
set.set(i);
}
}
return set;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted boolean array as object
*/
public static Object getBooleanArrayFromByteArray(byte[] buf)
{
int n = buf.length;
boolean[] a = new boolean[n];
for (int i = 0; i < n; i++)
{
a[i] = buf[i] != 0;
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromBooleanArray(Object value)
{
if (value == null)
{
return null;
}
boolean[] a = (boolean[]) value;
int n = a.length;
byte[] buf = new byte[n];
for (int i = 0; i < n; i++)
{
buf[i] = a[i] ? (byte) 1 : (byte) 0;
}
return buf;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted char array as object
*/
public static Object getCharArrayFromByteArray(byte[] buf)
{
int n = buf.length / 2;
char[] a = new char[n];
int i = 0;
int j = 0;
for (; i < n;)
{
a[i++] = (char) (((buf[j++] & 0xFF) << 8) + (buf[j++] & 0xFF));
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromCharArray(Object value)
{
if (value == null)
{
return null;
}
char[] a = (char[]) value;
int n = a.length;
byte[] buf = new byte[n * 2];
int i = 0;
int j = 0;
for (; i < n;)
{
char x = a[i++];
buf[j++] = (byte) ((x >>> 8) & 0xFF);
buf[j++] = (byte) (x & 0xFF);
}
return buf;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted double array as object
*/
public static Object getDoubleArrayFromByteArray(byte[] buf)
{
int n = buf.length / 8;
double[] a = new double[n];
int i = 0;
int j = 0;
for (; i < n;)
{
a[i++] = Double
.longBitsToDouble(((long) (buf[j++] & 0xFF) << 56) + ((long) (buf[j++] & 0xFF) << 48) + ((long) (buf[j++] & 0xFF) << 40) + ((long) (buf[j++] & 0xFF) << 32) + ((long) (buf[j++] & 0xFF) << 24) + ((buf[j++] & 0xFF) << 16) + ((buf[j++] & 0xFF) << 8) + (buf[j++] & 0xFF));
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromDoubleArray(Object value)
{
if (value == null)
{
return null;
}
double[] a = (double[]) value;
int n = a.length;
byte[] buf = new byte[n * 8];
int i = 0;
int j = 0;
for (; i < n;)
{
long x = Double.doubleToRawLongBits(a[i++]);
buf[j++] = (byte) ((x >>> 56) & 0xFF);
buf[j++] = (byte) ((x >>> 48) & 0xFF);
buf[j++] = (byte) ((x >>> 40) & 0xFF);
buf[j++] = (byte) ((x >>> 32) & 0xFF);
buf[j++] = (byte) ((x >>> 24) & 0xFF);
buf[j++] = (byte) ((x >>> 16) & 0xFF);
buf[j++] = (byte) ((x >>> 8) & 0xFF);
buf[j++] = (byte) (x & 0xFF);
}
return buf;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted float array as object
*/
public static Object getFloatArrayFromByteArray(byte[] buf)
{
int n = buf.length / 4;
float[] a = new float[n];
int i = 0;
int j = 0;
for (; i < n;)
{
a[i++] = Float.intBitsToFloat(((buf[j++] & 0xFF) << 24) + ((buf[j++] & 0xFF) << 16) + ((buf[j++] & 0xFF) << 8) + (buf[j++] & 0xFF));
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromFloatArray(Object value)
{
if (value == null)
{
return null;
}
float[] a = (float[]) value;
int n = a.length;
byte[] buf = new byte[n * 4];
int i = 0;
int j = 0;
for (; i < n;)
{
int x = Float.floatToRawIntBits(a[i++]);
buf[j++] = (byte) ((x >>> 24) & 0xFF);
buf[j++] = (byte) ((x >>> 16) & 0xFF);
buf[j++] = (byte) ((x >>> 8) & 0xFF);
buf[j++] = (byte) (x & 0xFF);
}
return buf;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted int array as object
*/
public static Object getIntArrayFromByteArray(byte[] buf)
{
int n = buf.length / 4;
int[] a = new int[n];
int i = 0;
int j = 0;
for (; i < n;)
{
a[i++] = ((buf[j++] & 0xFF) << 24) + ((buf[j++] & 0xFF) << 16) + ((buf[j++] & 0xFF) << 8) + (buf[j++] & 0xFF);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromIntArray(Object value)
{
if (value == null)
{
return null;
}
int[] a = (int[]) value;
int n = a.length;
byte[] buf = new byte[n * 4];
int i = 0;
int j = 0;
for (; i < n;)
{
int x = a[i++];
buf[j++] = (byte) ((x >>> 24) & 0xFF);
buf[j++] = (byte) ((x >>> 16) & 0xFF);
buf[j++] = (byte) ((x >>> 8) & 0xFF);
buf[j++] = (byte) (x & 0xFF);
}
return buf;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted long array as object
*/
public static Object getLongArrayFromByteArray(byte[] buf)
{
int n = buf.length / 8;
long[] a = new long[n];
int i = 0;
int j = 0;
for (; i < n;)
{
a[i++] = ((long) (buf[j++] & 0xFF) << 56) + ((long) (buf[j++] & 0xFF) << 48) + ((long) (buf[j++] & 0xFF) << 40) + ((long) (buf[j++] & 0xFF) << 32) + ((long) (buf[j++] & 0xFF) << 24) + ((buf[j++] & 0xFF) << 16) + ((buf[j++] & 0xFF) << 8) + (buf[j++] & 0xFF);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromLongArray(Object value)
{
if (value == null)
{
return null;
}
long[] a = (long[]) value;
int n = a.length;
byte[] buf = new byte[n * 8];
int i = 0;
int j = 0;
for (; i < n;)
{
long x = a[i++];
buf[j++] = (byte) ((x >>> 56) & 0xFF);
buf[j++] = (byte) ((x >>> 48) & 0xFF);
buf[j++] = (byte) ((x >>> 40) & 0xFF);
buf[j++] = (byte) ((x >>> 32) & 0xFF);
buf[j++] = (byte) ((x >>> 24) & 0xFF);
buf[j++] = (byte) ((x >>> 16) & 0xFF);
buf[j++] = (byte) ((x >>> 8) & 0xFF);
buf[j++] = (byte) (x & 0xFF);
}
return buf;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted short array as object
*/
public static Object getShortArrayFromByteArray(byte[] buf)
{
int n = buf.length / 2;
short[] a = new short[n];
int i = 0;
int j = 0;
for (; i < n;)
{
a[i++] = (short) (((buf[j++] & 0xFF) << 8) + (buf[j++] & 0xFF));
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromShortArray(Object value)
{
if (value == null)
{
return null;
}
short[] a = (short[]) value;
int n = a.length;
byte[] buf = new byte[n * 2];
int i = 0;
int j = 0;
for (; i < n;)
{
short x = a[i++];
buf[j++] = (byte) ((x >>> 8) & 0xFF);
buf[j++] = (byte) (x & 0xFF);
}
return buf;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromBigDecimalArray(Object value)
{
if (value == null)
{
return null;
}
BigDecimal[] a = (BigDecimal[]) value;
byte[] total = new byte[a.length * TOTAL_BYTES];
int index = 0;
for (int i=0; i < a.length; i++)
{
//set signal
System.arraycopy(new byte[] {(byte)a[i].signum()},0,total,index,NR_SIGNAL_BYTES);
index += NR_SIGNAL_BYTES;
//set big integer
byte[] b = a[i].unscaledValue().abs().toByteArray();
System.arraycopy(b,0,total,index+(NR_BIGINTEGER_BYTES-b.length),b.length);
index += NR_BIGINTEGER_BYTES;
//set scale
byte[] s = getByteArrayFromIntArray(new int[] { a[i].scale() });
System.arraycopy(s,0,total,index,NR_SCALE_BYTES);
index += NR_SCALE_BYTES;
}
return total;
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted BigDecimal array as object
*/
public static Object getBigDecimalArrayFromByteArray(byte[] buf)
{
BigDecimal[] a = new BigDecimal[buf.length/TOTAL_BYTES];
int index = 0;
for (int i=0; i < a.length; i++)
{
//get signal
byte[] signal = new byte[NR_SIGNAL_BYTES];
System.arraycopy(buf,index,signal,0,NR_SIGNAL_BYTES);
index += NR_SIGNAL_BYTES;
//get big integer
byte[] b = new byte[NR_BIGINTEGER_BYTES];
System.arraycopy(buf,index,b,0,NR_BIGINTEGER_BYTES);
BigInteger integer = new BigInteger(signal[0],b);
index += NR_BIGINTEGER_BYTES;
//get scale
byte[] s = new byte[4];
System.arraycopy(buf,index,s,0,NR_SCALE_BYTES);
int[] scale = (int[]) getIntArrayFromByteArray(s);
a[i] = new BigDecimal(integer,scale[0]);
index += NR_SCALE_BYTES;
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
*
* @param value Object to be converted
*
* @return converted byte array
*/
public static byte[] getByteArrayFromBigIntegerArray(Object value)
{
if (value == null)
{
return null;
}
BigInteger[] a = (BigInteger[]) value;
long[] d = new long[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].longValue();
}
return getByteArrayFromLongArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
*
* @param buf byte array to be converted
*
* @return converted short array as object
*/
public static Object getBigIntegerArrayFromByteArray(byte[] buf)
{
long[] d = (long[]) getLongArrayFromByteArray(buf);
BigInteger[] a = new BigInteger[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new BigInteger(""+d[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Boolean[] to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromBooleanObjectArray(Object value)
{
if (value == null)
{
return null;
}
Boolean[] a = (Boolean[]) value;
boolean[] d = new boolean[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].booleanValue();
}
return getByteArrayFromBooleanArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Boolean array as object
*/
public static Object getBooleanObjectArrayFromByteArray(byte[] buf)
{
boolean[] d = (boolean[]) getBooleanArrayFromByteArray(buf);
Boolean[] a = new Boolean[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Boolean(d[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Byte[] to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromByteObjectArray(Object value)
{
if (value == null)
{
return null;
}
Byte[] a = (Byte[]) value;
byte[] d = new byte[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].byteValue();
}
return d;
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Byte array as object
*/
public static Object getByteObjectArrayFromByteArray(byte[] buf)
{
if (buf == null)
{
return null;
}
Byte[] a = new Byte[buf.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Byte(buf[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Character array to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromCharObjectArray(Object value)
{
if (value == null)
{
return null;
}
Character[] a = (Character[]) value;
char[] d = new char[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].charValue();
}
return getByteArrayFromCharArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Character array as object
*/
public static Object getCharObjectArrayFromByteArray(byte[] buf)
{
char[] d = (char[]) getCharArrayFromByteArray(buf);
Character[] a = new Character[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Character(d[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Double array to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromDoubleObjectArray(Object value)
{
if (value == null)
{
return null;
}
Double[] a = (Double[]) value;
double[] d = new double[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].doubleValue();
}
return getByteArrayFromDoubleArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Double array as object
*/
public static Object getDoubleObjectArrayFromByteArray(byte[] buf)
{
double[] d = (double[]) getDoubleArrayFromByteArray(buf);
Double[] a = new Double[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Double(d[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Float array to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromFloatObjectArray(Object value)
{
if (value == null)
{
return null;
}
Float[] a = (Float[]) value;
float[] d = new float[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].floatValue();
}
return getByteArrayFromFloatArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Float array as object
*/
public static Object getFloatObjectArrayFromByteArray(byte[] buf)
{
float[] d = (float[]) getFloatArrayFromByteArray(buf);
Float[] a = new Float[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Float(d[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Integer array to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromIntObjectArray(Object value)
{
if (value == null)
{
return null;
}
Integer[] a = (Integer[]) value;
int[] d = new int[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].intValue();
}
return getByteArrayFromIntArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Integer array as object
*/
public static Object getIntObjectArrayFromByteArray(byte[] buf)
{
int[] d = (int[]) getIntArrayFromByteArray(buf);
Integer[] a = new Integer[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Integer(d[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Long array to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromLongObjectArray(Object value)
{
if (value == null)
{
return null;
}
Long[] a = (Long[]) value;
long[] d = new long[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].longValue();
}
return getByteArrayFromLongArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Long array as object
*/
public static Object getLongObjectArrayFromByteArray(byte[] buf)
{
long[] d = (long[]) getLongArrayFromByteArray(buf);
Long[] a = new Long[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Long(d[i]);
}
return a;
}
/**
* Convert an instance of our value class into a byte[].
* @param value Short array to be converted
* @return converted byte array
*/
public static byte[] getByteArrayFromShortObjectArray(Object value)
{
if (value == null)
{
return null;
}
Short[] a = (Short[]) value;
short[] d = new short[a.length];
for (int i=0; i < a.length; i++)
{
d[i] = a[i].shortValue();
}
return getByteArrayFromShortArray(d);
}
/**
* Convert a byte[] into an instance of our value class.
* @param buf byte array to be converted
* @return converted Short array as object
*/
public static Object getShortObjectArrayFromByteArray(byte[] buf)
{
short[] d = (short[]) getShortArrayFromByteArray(buf);
Short[] a = new Short[d.length];
for (int i=0; i < a.length; i++)
{
a[i] = new Short(d[i]);
}
return a;
}
/**
* Convert the value to a instance of the given type. The value converted only
* if the type can"t be assigned from the current type of the value instance.
* @param value the value to be converted
* @param type the type of the expected object returned from the coversion
* @return the converted object, or null if the object can"t be converted
*/
public static Object convertTo(Object value, Class type)
{
//check if the id can be assigned for the field type, otherwise convert the id to the appropriate type
if (!type.isAssignableFrom(value.getClass()))
{
if (type == short.class || type == Short.class)
{
return new Short(value.toString());
}
else if (type == char.class || type == Character.class)
{
return new Character(value.toString().charAt(0));
}
else if (type == int.class || type == Integer.class)
{
return new Integer(value.toString());
}
else if (type == long.class || type == Long.class)
{
return new Long(value.toString());
}
else if (type == boolean.class || type == Boolean.class)
{
return new Boolean(value.toString());
}
else if (type == byte.class || type == Byte.class)
{
return new Byte(value.toString());
}
else if (type == float.class || type == Float.class)
{
return new Float(value.toString());
}
else if (type == double.class || type == Double.class)
{
return new Double(value.toString());
}
else if (type == BigDecimal.class)
{
return new BigDecimal(value.toString());
}
else if (type == BigInteger.class)
{
return new BigInteger(value.toString());
}
else if (type == String.class)
{
return value.toString();
}
else
{
return null;
}
}
return value;
}
/**
* Utility to convert an int into a byte-generated String
* @param val The int
* @return The String form of the bytes
*/
public static String getStringFromInt(int val)
{
byte[] arr = new byte[4];
for (int i=3;i>=0;i--)
{
arr[i] = (byte) ((0xFFl & val) + Byte.MIN_VALUE);
val >>>= 8;
}
return new String(arr);
}
/**
* Utility to convert a short into a byte-generated String
* @param val The short
* @return The String form of the bytes
*/
public static String getStringFromShort(short val)
{
byte[] arr = new byte[2];
for (int i=1;i>=0;i--)
{
arr[i] = (byte) ((0xFFl & val) + Byte.MIN_VALUE);
val >>>= 8;
}
return new String(arr);
}
/**
* Utility to convert an int into a 8-char hex String
* @param val The int
* @return The hex String form of the int
*/
public static String getHexFromInt(int val)
{
StringBuffer str = new StringBuffer("00000000");
String hexstr = Integer.toHexString(val);
str.replace(8 - hexstr.length(), 8, hexstr);
return str.toString();
}
/**
* Utility to convert a short into a 4-char hex String
* @param val The short
* @return The hex String form of the short
*/
public static String getHexFromShort(short val)
{
StringBuffer str = new StringBuffer("0000");
String hexstr = Integer.toHexString(val);
str.replace(4 - hexstr.length(), 4, hexstr);
return str.toString();
}
/**
* Utility to convert a byte array to an int.
* @param bytes The byte array
* @return The int
*/
public static int getIntFromByteArray(byte[] bytes)
{
int val = 0;
for (int i=0; i<4; i++)
{
val = (val << 8) - Byte.MIN_VALUE + bytes[i];
}
return val;
}
/**
* Converts a string in JDBC timestamp escape format to a Timestamp object.
* To be precise, we prefer to find a JDBC escape type sequence in the format
* "yyyy-mm-dd hh:mm:ss.fffffffff", but this does accept other separators
* of fields, so as long as the numbers are in the order
* year, month, day, hour, minute, second then we accept it.
* @param s Timestamp string
* @param cal The Calendar to use for conversion
* @return Corresponding <tt>java.sql.Timestamp</tt> value.
* @exception java.lang.IllegalArgumentException Thrown if the format of the
* String is invalid
*/
public static Timestamp stringToTimestamp(String s, Calendar cal)
{
int[] numbers = convertStringToIntArray(s);
if (numbers == null || numbers.length < 6)
{
throw new IllegalArgumentException("string to time stamp"+ s);
}
int year = numbers[0];
int month = numbers[1];
int day = numbers[2];
int hour = numbers[3];
int minute = numbers[4];
int second = numbers[5];
int nanos = 0;
if (numbers.length > 6)
{
nanos = numbers[6];
}
Calendar thecal = cal;
if (cal == null)
{
thecal = new GregorianCalendar();
}
thecal.set(Calendar.ERA, GregorianCalendar.AD);
thecal.set(Calendar.YEAR, year);
thecal.set(Calendar.MONTH, month - 1);
thecal.set(Calendar.DATE, day);
thecal.set(Calendar.HOUR_OF_DAY, hour);
thecal.set(Calendar.MINUTE, minute);
thecal.set(Calendar.SECOND, second);
Timestamp ts = new Timestamp(thecal.getTime().getTime());
ts.setNanos(nanos);
return ts;
}
/**
* Convenience method to convert a String containing numbers (separated by assorted
* characters) into an int array. The separators can be " " "-" ":" "." "," etc.
* @param str The String
* @return The int array
*/
private static int[] convertStringToIntArray(String str)
{
if (str == null)
{
return null;
}
int[] values = null;
ArrayList list = new ArrayList();
int start = -1;
for (int i=0;i<str.length();i++)
{
if (start == -1 && Character.isDigit(str.charAt(i)))
{
start = i;
}
if (start != i && start >= 0)
{
if (!Character.isDigit(str.charAt(i)))
{
list.add(new Integer(str.substring(start, i)));
start = -1;
}
}
}
if (list.size() > 0)
{
values = new int[list.size()];
Iterator iter = list.iterator();
int n = 0;
while (iter.hasNext())
{
values[n++] = ((Integer)iter.next()).intValue();
}
}
return values;
}
/** Used to zero-fill the fractional seconds to nine digits. */
private static final String ZEROES = "000000000";
/**
* Formats a timestamp in JDBC timestamp escape format using the timezone
* of the passed Calendar.
* @param ts The timestamp to be formatted.
* @param cal The Calendar
* @return A String in <tt>yyyy-mm-dd hh:mm:ss.fffffffff</tt> format.
* @see java.sql.Timestamp
*/
public static String timestampToString(Timestamp ts, Calendar cal)
{
cal.setTime(ts);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; // Months are zero based in Calendar
int day = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
String yearString = Integer.toString(year);
String monthString = month < 10 ? "0" + month : Integer.toString(month);
String dayString = day < 10 ? "0" + day : Integer.toString(day);
String hourString = hour < 10 ? "0" + hour : Integer.toString(hour);
String minuteString = minute < 10 ? "0" + minute : Integer.toString(minute);
String secondString = second < 10 ? "0" + second : Integer.toString(second);
String nanosString = Integer.toString(ts.getNanos());
if (ts.getNanos() != 0)
{
// Add leading zeroes
nanosString = ZEROES.substring(0, ZEROES.length() - nanosString.length()) + nanosString;
// Truncate trailing zeroes
int truncIndex = nanosString.length() - 1;
while (nanosString.charAt(truncIndex) == "0")
{
--truncIndex;
}
nanosString = nanosString.substring(0, truncIndex + 1);
}
return (yearString + "-" + monthString + "-" + dayString + " " + hourString + ":" + minuteString + ":" + secondString + "." + nanosString);
}
/**
* Convert a string into an integer.
* Returns the default value if not convertable.
* @param str The string
* @param dflt The default value
* @return The converted int value
*/
public static int intFromString(String str, int dflt)
{
try
{
Integer val = new Integer(str);
return val.intValue();
}
catch (NumberFormatException nfe)
{
return dflt;
}
}
}
Conversion utilities
/*
* Copyright (c) 2002,2003 Free Software Foundation
* developed under the custody of the
* Open Web Application Security Project
* (http://www.owasp.org)
*
* This file is part of the OWASP common library (OCL).
* OCL is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* OCL 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.
* See the GNU General Public License for more details.
*
* The valid license text for this file can be retrieved with
* the call: java -cp owasp.jar org.owasp.LICENSE
*
* If you are not able to view the LICENSE that way, which should
* always be possible within a valid and working OCL release,
* please write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* to get a copy of the GNU General Public License or to report a
* possible license violation.
*/
import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Conversion utilities.
*
* @since beta 1
* @version beta 1<br />CVS $Revision: 1.8 $ $Author: istr $
* @author
*/
public final class Convert {
/** Revision identifier */
public static final String MODULE = "<Convert beta 1, CVS $Revision: 1.8 $>";
/** to mimic sizeof(short) = short length in bytes = 12 (=16bit) */
public static final int SIZEOF_SHORT = 2;
/** to mimic sizeof(int) = int length in bytes = 4 (=32bit) */
public static final int SIZEOF_INT = 4;
/** to mimic sizeof(long) = long length in bytes = 8 (=64bit) */
public static final int SIZEOF_LONG = 8;
/** bit length of byte */
public static final int BITS_BYTE = 8;
/** bit length of short */
public static final int BITS_SHORT = BITS_BYTE * SIZEOF_SHORT;
/** bit length of int */
public static final int BITS_INT = BITS_BYTE * SIZEOF_INT;
/** bit length of long */
public static final int BITS_LONG = BITS_BYTE * SIZEOF_LONG;
/** mask a byte in an int */
public static final int MASK_BYTE = 0xFF;
/** Avoids instantiation */
private Convert () {}
/**
* Converts the SIZEOF_LONG bytes starting at off within b to a long value.
* <br />NOTE: the conversion treats the leftmost byte as the lowest byte of
* the resulting long value
* @param b a byte[] containing bytes to be converted
* @param off the offset where to find the bytes to be converted
* @return a long value
* @throws IndexOutOfBoundsException if an index violation occurs
*/
public static long toLong ( byte[] b, int off ) {
long r = 0;
for ( int i = SIZEOF_LONG - 1; i >= 0; i-- )
r |= (((long) b[ off + i ]) & MASK_BYTE) << (i*BITS_BYTE);
return r;
}
/**
* Converts the SIZEOF_INT bytes starting at off within b to an int value.
* <br />NOTE: the conversion treats the leftmost byte as the lowest byte of
* the resulting int value
* @param b a byte[] containing bytes to be converted
* @param off the offset where to find the bytes to be converted
* @return an int value
* @throws IndexOutOfBoundsException if an index violation occurs
*/
public static int toInt ( byte[] b, int off ) {
int r = 0;
for ( int i = SIZEOF_INT - 1; i >= 0; i-- )
r |= ((int) (b[ off + i ] & MASK_BYTE)) << (i*BITS_BYTE);
return r;
}
/**
* Converts a long value to SIZEOF_LONG bytes stored in b starting at off.
* <br />NOTE: the conversion stores the lowest byte of the long value as
* the leftmost byte within the sequence
* @param val a long value to be split up into bytes
* @param b a byte[] to be written to
* @param off the offset where to start writing within b
* @throws IndexOutOfBoundsException if an index violation occurs
*/
public static void toBytes ( long val, byte[] b, int off ) {
for ( int i = 0; i < SIZEOF_LONG; i++, val >>= BITS_BYTE )
b[ off + i ] = (byte) (val & MASK_BYTE);
}
/**
* Converts an int value to SIZEOF_INT bytes stored in b starting at off.
* <br />NOTE: the conversion stores the lowest byte of the int value as
* the leftmost byte within the sequence
* @param val an int value to be split up into bytes
* @param b a byte[] to be written to
* @param off the offset where to start writing within b
* @throws IndexOutOfBoundsException if an index violation occurs
*/
public static void toBytes ( int val, byte[] b, int off ) {
for ( int i = 0; i < SIZEOF_INT; i++, val >>= BITS_BYTE )
b[ off + i ] = (byte) (val & MASK_BYTE);
}
/**
* Converts a byte value to a hexadecimal String.
* @param b a byte value
* @return a hexadecimal (upper-case-based) String representation of the
* byte value
*/
public static String toHexString ( byte b ) {
int len = 2;
byte[] dig = new byte[ len ];
dig[ 0 ] = (byte) ((b & 0xF0) >> 4);
dig[ 1 ] = (byte) (b & 0x0F);
for ( int i = 0; i < len; i++ )
dig[ i ] += 10 > dig[ i ] ? 48 : 55;
return new String( dig );
}
public static String toHexString ( byte[] b ) {
if ( null == b )
return null;
int len = b.length;
byte[] hex = new byte[ len << 1 ];
for ( int i = 0, j = 0; i < len; i++, j+=2 ) {
hex[ j ] = (byte) ((b[ i ] & 0xF0) >> 4);
hex[ j ] += 10 > hex[ j ] ? 48 : 55;
hex[ j + 1 ] = (byte) (b[ i ] & 0x0F);
hex[ j + 1 ] += 10 > hex[ j + 1 ] ? 48 : 55;
}
return new String( hex );
}
/**
* Parses a number from a string.
* Finds the first recognizable base-10 number (integer or floating point)
* in the string and returns it as a Number.
* @param string String to parse
* @return first recognizable number
* @exception NumberFormatException if no recognizable number is found
*/
public static Number toNumber ( String s )
throws NumberFormatException
{
// parsing states
int INT = 0;
int FRAC = 1;
int EXP = 2;
int p = 0;
for ( int i = 0; i < s.length(); ++i ) {
char c = s.charAt( i );
if ( Character.isDigit( c ) ) {
int start = i;
int end = ++i;
int state = INT;
if ( start > 0 && s.charAt( start - 1 ) == "." ) {
--start;
state = FRAC;
}
if ( start > 0 && s.charAt( start - 1 ) == "-" )
--start;
boolean atEnd = false;
while ( !atEnd && i < s.length() ) {
switch ( s.charAt( i ) ) {
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
end = ++i;
break;
case ".":
if ( state == INT ) {
state = FRAC;
++i;
} else {
atEnd = true;
}
break;
case "e":
case "E":
state = EXP;
++i;
if ( i < s.length() && ((c = s.charAt( i )) == "+" || c == "-") )
++i;
break;
default:
atEnd = true;
}
}
String num = s.substring( start, end );
try {
if ( state == INT )
return new Integer( num );
else
return new Double( num );
}
catch ( NumberFormatException e ) {
throw new RuntimeException( "internal error: " + e );
}
}
}
throw new NumberFormatException( s );
}
public static String[] toStrings( Object[] o ) {
if ( null == o )
return null;
int len = o.length;
String[] s = new String[ len ];
for ( int i = 0; i < len; i++ )
if ( null != o[ i ] )
s[ i ] = o[ i ].toString();
return s;
}
/** converts to int with radix 10 and default 0 */
public static int toInt ( Object o ) {
return toInt( o, 10, 0 );
}
/**
* Convets an Object to an int value using radix 10.
* <br />This is a wrapper for
* <code>{@link #toInt( Object, int ) toInt( o, 10 )}</code>.
* @param o Object to be converted to integer
* @return the int value represented by o or 0 if conversion fails.
*/
public static int toInt ( Object o, int dflt ) {
return toInt( o, 10, dflt );
}
/**
* Converts any String representation to an int value using a given radix.
* <br />For <code>null</code> it returns <code>0</code>.<br />
* For Objects instanceof Number it returns the Object"s
* <code>intValue()</code>.
* For all other Objects it uses the <code>toString()</code> method to get an
* appropriate String representation and parses this String using
* <code>Integer.parseInt</code>.
* If conversion fails it returns <code>0</code>.
* @param o Object to be converted to integer
* @param radix the radix used for conversion
* @return the int value represented by <code>o</code> or <code>0</code>
* if conversion fails.
*/
public static int toInt ( Object o, int radix, int dflt ) {
if ( null == o ) // shortcut without exception
return dflt;
if ( o instanceof Number )
return ((Number) o).intValue();
try {
return Integer.parseInt( o.toString().trim(), radix );
}
catch ( Exception e ) {
return dflt;
}
}
public static long toLong ( Object o ) {
return toLong( o, 10, 0 );
}
public static long toLong ( Object o, int dflt ) {
return toLong( o, 10, dflt );
}
public static long toLong ( Object o, int radix, int dflt ) {
if ( null == o ) // shortcut without exception
return dflt;
if ( o instanceof Number )
return ((Number) o).longValue();
try {
return Long.parseLong( o.toString().trim(), radix );
}
catch ( Exception e ) {
return dflt;
}
}
} // class Convert
Convert Byte array to Int
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program 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. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
public final class BytesHelper {
private BytesHelper() {}
public static int toInt( byte[] bytes ) {
int result = 0;
for (int i=0; i<4; i++) {
result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}
}
Convert byte array to Long
public class Util {
public static long toLong(byte[] b) {
long n = (long) (b[0] & 0xff) << 56 | (long) (b[1] & 0xff) << 48
| (long) (b[2] & 0xff) << 40 | (long) (b[3] & 0xff) << 32
| (long) (b[4] & 0xff) << 24 | (long) (b[5] & 0xff) << 16
| (long) (b[6] & 0xff) << 8 | (long) (b[7] & 0xff);
return n;
}
}
Convert long to Bytes
public class Util {
public static byte[] toBytes(long n) {
byte[] b = new byte[8];
b[0] = (byte) (n >>> 56);
b[1] = (byte) (n >>> 48);
b[2] = (byte) (n >>> 40);
b[3] = (byte) (n >>> 32);
b[4] = (byte) (n >>> 24);
b[5] = (byte) (n >>> 16);
b[6] = (byte) (n >>> 8);
b[7] = (byte) (n);
return b;
}
}
Convert Number To Target Class
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;
/**
* Miscellaneous utility methods for number conversion and parsing.
* Mainly for internal use within the framework; consider Jakarta"s
* Commons Lang for a more comprehensive suite of string utilities.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @since 1.1.2
*/
public abstract class NumberUtils {
/**
* Convert the given number into an instance of the given target class.
*
* @param number the number to convert
* @param targetClass the target class to convert to
* @return the converted number
* @throws IllegalArgumentException if the target class is not supported
* (i.e. not a standard Number subclass as included in the JDK)
* @see java.lang.Byte
* @see java.lang.Short
* @see java.lang.Integer
* @see java.lang.Long
* @see java.math.BigInteger
* @see java.lang.Float
* @see java.lang.Double
* @see java.math.BigDecimal
*/
public static Number convertNumberToTargetClass(Number number, Class targetClass)
throws IllegalArgumentException {
if (targetClass.isInstance(number)) {
return number;
} else if (targetClass.equals(Byte.class)) {
long value = number.longValue();
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return number.byteValue();
} else if (targetClass.equals(Short.class)) {
long value = number.longValue();
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return number.shortValue();
} else if (targetClass.equals(Integer.class)) {
long value = number.longValue();
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return number.intValue();
} else if (targetClass.equals(Long.class)) {
return number.longValue();
} else if (targetClass.equals(Float.class)) {
return number.floatValue();
} else if (targetClass.equals(Double.class)) {
return number.doubleValue();
} else if (targetClass.equals(BigInteger.class)) {
return BigInteger.valueOf(number.longValue());
} else if (targetClass.equals(BigDecimal.class)) {
// using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
// (see BigDecimal javadoc for details)
return new BigDecimal(number.toString());
} else {
throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
}
}
/**
* Raise an overflow exception for the given number and target class.
*
* @param number the number we tried to convert
* @param targetClass the target class we tried to convert to
*/
private static void raiseOverflowException(Number number, Class targetClass) {
throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
}
/**
* Parse the given text into a number instance of the given target class,
* using the corresponding default <code>decode</code> methods. Trims the
* input <code>String</code> before attempting to parse the number. Supports
* numbers in hex format (with leading 0x) and in octal format (with leading 0).
*
* @param text the text to convert
* @param targetClass the target class to parse into
* @return the parsed number
* @throws IllegalArgumentException if the target class is not supported
* (i.e. not a standard Number subclass as included in the JDK)
* @see java.lang.Byte#decode
* @see java.lang.Short#decode
* @see java.lang.Integer#decode
* @see java.lang.Long#decode
* @see #decodeBigInteger(String)
* @see java.lang.Float#valueOf
* @see java.lang.Double#valueOf
* @see java.math.BigDecimal#BigDecimal(String)
*/
public static Number parseNumber(String text, Class targetClass) {
String trimmed = text.trim();
if (targetClass.equals(Byte.class)) {
return Byte.decode(trimmed);
} else if (targetClass.equals(Short.class)) {
return Short.decode(trimmed);
} else if (targetClass.equals(Integer.class)) {
return Integer.decode(trimmed);
} else if (targetClass.equals(Long.class)) {
return Long.decode(trimmed);
} else if (targetClass.equals(BigInteger.class)) {
return decodeBigInteger(trimmed);
} else if (targetClass.equals(Float.class)) {
return Float.valueOf(trimmed);
} else if (targetClass.equals(Double.class)) {
return Double.valueOf(trimmed);
} else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
return new BigDecimal(trimmed);
} else {
throw new IllegalArgumentException(
"Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
}
}
/**
* Parse the given text into a number instance of the given target class,
* using the given NumberFormat. Trims the input <code>String</code>
* before attempting to parse the number.
*
* @param text the text to convert
* @param targetClass the target class to parse into
* @param numberFormat the NumberFormat to use for parsing (if <code>null</code>,
* this method falls back to <code>parseNumber(String, Class)</code>)
* @return the parsed number
* @throws IllegalArgumentException if the target class is not supported
* (i.e. not a standard Number subclass as included in the JDK)
* @see java.text.NumberFormat#parse
* @see #convertNumberToTargetClass
* @see #parseNumber(String,Class)
*/
public static Number parseNumber(String text, Class targetClass, NumberFormat numberFormat) {
if (numberFormat != null) {
try {
Number number = numberFormat.parse(text.trim());
return convertNumberToTargetClass(number, targetClass);
}
catch (ParseException ex) {
throw new IllegalArgumentException(ex.getMessage());
}
} else {
return parseNumber(text, targetClass);
}
}
/**
* Decode a {@link java.math.BigInteger} from a {@link String} value.
* Supports decimal, hex and octal notation.
*
* @see BigInteger#BigInteger(String,int)
*/
private static BigInteger decodeBigInteger(String value) {
int radix = 10;
int index = 0;
boolean negative = false;
// Handle minus sign, if present.
if (value.startsWith("-")) {
negative = true;
index++;
}
// Handle radix specifier, if present.
if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
index += 2;
radix = 16;
} else if (value.startsWith("#", index)) {
index++;
radix = 16;
} else if (value.startsWith("0", index) && value.length() > 1 + index) {
index++;
radix = 8;
}
BigInteger result = new BigInteger(value.substring(index), radix);
return (negative ? result.negate() : result);
}
}
Data type conversion
/*
*
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
*
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowlegement:
* "This product includes software developed by independent contributors
* and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
* or promote products derived from this software without prior written
* permission. For written permission, email
* "andrus at objectstyle dot org".
*
* 5. Products derived from this software may not be called "ObjectStyle"
* or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
* names without prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site. For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* A collection of static conversion utility methods.
*
* @since 1.1
* @author Andrei Adamchik
*/
public final class ConversionUtil {
public static int toInt(Object object, int defaultValue) {
if (object == null) {
return defaultValue;
}
else if (object instanceof Number) {
return ((Number) object).intValue();
}
else if (object instanceof String) {
try {
return Integer.parseInt((String) object);
}
catch (NumberFormatException ex) {
return defaultValue;
}
}
return defaultValue;
}
public static boolean toBoolean(Object object) {
if (object instanceof Boolean) {
return ((Boolean) object).booleanValue();
}
if (object instanceof Number) {
return ((Number) object).intValue() != 0;
}
return object != null;
}
public static BigDecimal toBigDecimal(Object object) {
if (object == null) {
return null;
}
else if (object instanceof BigDecimal) {
return (BigDecimal) object;
}
else if (object instanceof BigInteger) {
return new BigDecimal((BigInteger) object);
}
else if (object instanceof Number) {
return new BigDecimal(((Number) object).doubleValue());
}
throw new Exception("Can"t convert to BigDecimal: " + object);
}
/**
* Attempts to convert an object to Comparable instance.
*/
public static Comparable toComparable(Object object) {
if (object == null) {
return null;
}
else if (object instanceof Comparable) {
return (Comparable) object;
}
else if (object instanceof StringBuffer) {
return object.toString();
}
else if (object instanceof char[]) {
return new String((char[]) object);
}
else {
throw new ClassCastException(
"Invalid Comparable class:" + object.getClass().getName());
}
}
/**
* Attempts to convert an object to Comparable instance.
*/
public static String toString(Object object) {
if (object == null) {
return null;
}
else if (object instanceof String) {
return (String) object;
}
else if (object instanceof StringBuffer) {
return object.toString();
}
else if (object instanceof char[]) {
return new String((char[]) object);
}
else {
throw new ClassCastException(
"Invalid class for String conversion:" + object.getClass().getName());
}
}
/**
* Attempts to convert an object to an uppercase string.
*/
public static Object toUpperCase(Object object) {
if ((object instanceof String) || (object instanceof StringBuffer)) {
return object.toString().toUpperCase();
}
else if (object instanceof char[]) {
return new String((char[]) object).toUpperCase();
}
else {
return object;
}
}
private ConversionUtil() {
}
}
Data type Conversion Util
/*
* ConversionUtil.java
*
* Created on May 28, 2006, 12:02 PM
*
*
Copyright (c) 2006, Mark Martin
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of the JOCP Project nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.nio.ByteBuffer;
/**
*
* @author mark
*/
public class ConversionUtil {
/** Creates a new instance of ConversionUtil */
public ConversionUtil() {
}
public static byte[] convertToByteArray(byte value) {
byte[] array = new byte[1];
array[0] = value;
return array;
}
public static byte[] convertToByteArray(char value) {
byte[] bytes = new byte[2];
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.putChar(value);
return buffer.array();
// buffer.get(bytes);
/*
for (int i =0;i<bytes.length; ++i) {
int offset = (bytes.length -i-1) *8;
bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
**/
// return bytes;
}
public static byte[] convertToByteArray(int value) {
byte[] bytes = new byte[4];
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.putInt(value);
return buffer.array();
// buffer.get(bytes);
/*
for (int i =0;i<bytes.length; ++i) {
int offset = (bytes.length -i-1) *8;
bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
*/
// return bytes;
}
public static byte[] convertToByteArray(long value) {
byte[] bytes = new byte[8];
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.putLong(value);
return buffer.array();
// buffer.get(bytes);
/*
for (int i =0;i<bytes.length; ++i) {
int offset = (bytes.length -i-1) *8;
bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
*/
// return bytes;
}
public static byte[] convertToByteArray(short value) {
byte[] bytes = new byte[2];
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.putShort(value);
return buffer.array();
// buffer.get(bytes);
/*
for (int i =0;i<bytes.length; ++i) {
int offset = (bytes.length -i-1) *8;
bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
*/
// return bytes;
}
public static byte[] convertToByteArray(float value) {
byte[] bytes = new byte[4];
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.putFloat(value);
return buffer.array();
// buffer.get(bytes);
// return bytes;
// return convertToByteArray(Float.floatToIntBits(value));
}
public static byte[] convertToByteArray(double value) {
byte[] bytes = new byte[8];
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.putDouble(value);
return buffer.array();
// buffer.get(bytes);
// return bytes;
//return convertToByteArray(Double.doubleToLongBits(value));
}
public static byte[] convertToByteArray(String value) {
return value.getBytes();
}
public static byte[] convertToByteArray(boolean value) {
byte[] array = new byte[1];
array[0] = (byte)(value == true ? 1 : 0);
return array;
}
public static byte convertToByte(byte[] array) {
return array[0];
}
public static int convertToInt(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
return buffer.getInt();
/*
int value = 0;
for (int i =0;i<array.length; ++i) {
int offset = (array.length -i-1) *8;
value += (array[i] << offset);
// bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
return value;
**/
}
public static long convertToLong(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
return buffer.getLong();
/*
long value = 0;
for (int i =0;i<array.length; ++i) {
int offset = (array.length -i-1) *8;
value += (array[i] << offset);
// bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
return value;
*/
}
public static short convertToShort(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
return buffer.getShort();
/*
short value = 0;
for (int i =0;i<array.length; ++i) {
int offset = (array.length -i-1) *8;
value += (array[i] << offset);
// bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
return value;
*/
}
public static String convertToString(byte[] array) {
String value = new String(array);
return value;
}
public static Object convertToValue(Class aClass, byte[] inputArray) throws Exception {
Object returnValue = null;
String className = aClass.getName();
if (className.equals(Integer.class.getName())) {
returnValue = new Integer(convertToInt(inputArray));
} else if (className.equals(String.class.getName())) {
returnValue = convertToString(inputArray);
} else if (className.equals(Byte.class.getName())) {
returnValue = new Byte(convertToByte(inputArray));
} else if (className.equals(Long.class.getName())) {
returnValue = new Long(convertToLong(inputArray));
} else if (className.equals(Short.class.getName())) {
returnValue = new Short(convertToShort(inputArray));
} else if (className.equals(Boolean.class.getName())) {
returnValue = new Boolean(convertToBoolean(inputArray));
}else {
throw new Exception("Cannot convert object of type " + className);
}
return returnValue;
}
public static byte[] convertToByteArray(Object object) throws Exception {
byte[] returnArray = null;
Class clazz = object.getClass();
String clazzName = clazz.getName();
if (clazz.equals(Integer.class)) {
Integer aValue = (Integer)object;
int intValue = aValue.intValue();
returnArray = convertToByteArray(intValue);
} else if (clazz.equals(String.class)) {
String aValue = (String)object;
returnArray = convertToByteArray(aValue);
} else if (clazz.equals(Byte.class)) {
Byte aValue = (Byte)object;
byte byteValue = aValue.byteValue();
returnArray = convertToByteArray(byteValue);
} else if (clazz.equals(Long.class)) {
Long aValue = (Long)object;
long longValue = aValue.longValue();
returnArray = convertToByteArray(longValue);
} else if (clazz.equals(Short.class)) {
Short aValue = (Short)object;
short shortValue = aValue.shortValue();
returnArray = convertToByteArray(shortValue);
} else if (clazz.equals(Boolean.class)) {
Boolean aValue = (Boolean)object;
boolean booleanValue = aValue.booleanValue();
returnArray = convertToByteArray(booleanValue);
} else if (clazz.equals(Character.class)) {
Character aValue = (Character)object;
char charValue = aValue.charValue();
returnArray = convertToByteArray(charValue);
} else if (clazz.equals(Float.class)) {
Float aValue = (Float)object;
float floatValue = aValue.floatValue();
returnArray = convertToByteArray(floatValue);
} else if (clazz.equals(Double.class)) {
Double aValue = (Double)object;
double doubleValue = aValue.doubleValue();
returnArray = convertToByteArray(doubleValue);
} else {
throw new Exception("Cannot convert object of type " + clazzName);
}
return returnArray;
}
public static boolean convertToBoolean(byte[] array) {
return (array[0] > 0 ? true : false );
}
public static char convertToCharacter(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
return buffer.getChar();
/*
char value = 0;
for (int i =0;i<array.length; ++i) {
int offset = (array.length -i-1) *8;
value += (array[i] << offset);
// bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
}
return value;
*/
}
public static double convertToDouble(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
return buffer.getDouble();
/*
long longValue = convertToLong(array);
return Double.longBitsToDouble(longValue);
*/
}
public static float convertToFloat(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
return buffer.getFloat();
/*
int intValue = convertToInt(array);
return Float.intBitsToFloat(intValue);
*/
}
}
Get the minimum and maximum value of a primitive data types?
public class Main {
public static void main(String[] args) {
System.out.println("Byte.MIN = " + Byte.MIN_VALUE);
System.out.println("Byte.MAX = " + Byte.MAX_VALUE);
System.out.println("Short.MIN = " + Short.MIN_VALUE);
System.out.println("Short.MAX = " + Short.MAX_VALUE);
System.out.println("Integer.MIN = " + Integer.MIN_VALUE);
System.out.println("Integer.MAX = " + Integer.MAX_VALUE);
System.out.println("Long.MIN = " + Long.MIN_VALUE);
System.out.println("Long.MAX = " + Long.MAX_VALUE);
System.out.println("Float.MIN = " + Float.MIN_VALUE);
System.out.println("Float.MAX = " + Float.MAX_VALUE);
System.out.println("Double.MIN = " + Double.MIN_VALUE);
System.out.println("Double.MAX = " + Double.MAX_VALUE);
}
}