2011年1月8日 星期六

java的資料型別轉換

2005Java資料型別轉換 (從Fred, http://fredwang.blogspot.com/2005/07/java.html參考)
這是一些簡單常用的Java資料型別轉換

Java資料型別轉換

數字轉字串
1. integer to String :

int i = 20;
String str = Integer.toString(i);
or
String str = "" + i

2. double to String :

String str = Double.toString(i);

3. long to String :

String str = Long.toString(l);

4. float to String :

String str = Float.toString(f);

字串轉數字
1.String to integer :

str = "20";
int i = Integer.valueOf(str).intValue();
or
int i = Integer.parseInt(str);

2.String to double :

double d = Double.valueOf(str).doubleValue();

3. String to long :

long l = Long.valueOf(str).longValue();
or
long l = Long.parseLong(str);

4.String to float :

float f = Float.valueOf(str).floatValue();

十進位,二進位與十六進位數字的轉換
1. decimal to binary :

int i = 20;
String binstr = Integer.toBinaryString(i);

2. decimal to hexadecimal :

int i = 20;
String hexstr = Integer.toString(i, 16);

or
String hexstr = Integer.toHexString(i);

or (with leading zeroes and uppercase)
public class Hex {
public static void main(String args[]){
int i = 20;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}

3. hexadecimal (String) to integer :

int i = Integer.valueOf("B8DA3", 16).intValue();
or
int i = Integer.parseInt("B8DA3", 16);


ASCII Code的轉換
1.ASCII code to String

int i = 64;
String aChar = new Character((char)i).toString();

2.integer to ASCII code (byte)

char c = 'A';
int i = (int) c; // i will have the value 65 decimal

3.To extract Ascii codes from a String

String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) { char c = test.charAt( i ); int i = (int) c; System.out.println(i); } Boolean值的轉換
1.integer to boolean

b = (i != 0);

2.boolean to integer

i = (b)?1:0;

數字轉換錯誤處理
note :To catch illegal number conversion, try using the try/catch mechanism.

try{
i = Integer.parseInt(aString);
}
catch(NumberFormatException e)
{
}

日期與字串的轉換 (For J2SE 1.4.2)
1. Date to String

Date dNow = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
StringBuffer sbNow = new StringBuffer();
sbNow = formatter.format(dNow, sbNow, new FieldPosition(0));
String sNow = sbNow.toString();

2. String to Date

String sDate = "2005-01-01";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dDate = formatter.parse(sDate,new ParsePosition(0));

沒有留言:

張貼留言