十进制转成十六进制:
Integer.toHexString(int i)
十进制转成八进制
Integer.toOctalString(int i)
十进制转成二进制
Integer.toBinaryString(int i)
十六进制转成十进制
Integer.valueOf("FFFF",16).toString()
八进制转成十进制
Integer.valueOf("876",8).toString()
二进制转十进制
Integer.valueOf("0101",2).toString()
有什么方法可以直接将2,8,16进制直接转换为10进制的吗?
java.lang.Integer类
parseInt(String s, int radix)
使用第二个参数指定的基数,将字符串参数解析为有符号的整数。
examples from jdk:
parseInt("0", 10) returns 0
parseInt("473", 10) returns 473
parseInt("-0", 10) returns 0
parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
parseInt("2147483647", 10) returns 2147483647
parseInt("-2147483648", 10) returns -2147483648
parseInt("2147483648", 10) throws a NumberFormatException
parseInt("99", 8) throws a NumberFormatException
parseInt("Kona", 10) throws a NumberFormatException
parseInt("Kona", 27) returns 411787
进制转换如何写(二,八,十六)不用算法
Integer.toBinaryString
Integer.toOctalString
Integer.toHexString
例一:
public class Test{
public static void main(String args[]){
int i=100;
String binStr=Integer.toBinaryString(i);
String otcStr=Integer.toOctalString(i);
String hexStr=Integer.toHexString(i);
System.out.println(binStr);
例二:
public class TestStringFormat {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("usage: java TestStringFormat <a number>");
System.exit(0);
}
Integer factor = Integer.valueOf(args[0]);
String s;
s = String.format("%d", factor);
System.out.println(s);
s = String.format("%x", factor);
System.out.println(s);
s = String.format("%o", factor);
System.out.println(s);
}
}
1.得到当前月的第一天和最后一天,注意3是4月份,从零开始
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2007);
c.set(Calendar.MONTH, 3);
System.out.println(c.getActualMaximum(c.DAY_OF_MONTH));
System.out.println(c.getActualMinimum(c.DAY_OF_MONTH));
2.十六进制的转换
String st = "this is roger";
// hex
for(int i = 0; i<st.length(); i++){
System.out.println();
int ch=(int)st.charAt( i );
String s4="00"+Integer.toHexString( ch );
System.out.println(i + "output->"+s4); // String to Hex
//back String
int intVal = Integer.parseInt(s4, 16);
char charVal = (char) intVal;
System.out.println("The character is: "+charVal);
}
int temp = 1234567;
String hexString = Integer.toHexString(temp);
System.out.println( "hexString = " + hexString );
String str = Integer.toString(Integer.parseInt(hexString, 16));
System.out.println( "str = " + str );
/ 转化十六进制编码为字符串
public static String toStringHex(String s)
{
byte[] baKeyword = new byte[s.length()/2];
for(int i = 0; i < baKeyword.length; i++)
{
try
{
baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
}
catch(Exception e)
{
e.printStackTrace();
}
}
try
{
s = new String(baKeyword, "utf-8");//UTF-16le:Not
}
catch (Exception e1)
{
e1.printStackTrace();
}
return s;
}
public static void main(String[] args) {
System.out.println(encode("中文"));
System.out.println(decode(encode("中文")));
}
/*
* 16进制数字字符集
*/
private static String hexString="0123456789ABCDEF";
/*
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
*/
public static String encode(String str)
{
//根据默认编码获取字节数组
byte[] bytes=str.getBytes();
StringBuilder sb=new StringBuilder(bytes.length*2);
//将字节数组中每个字节拆解成2位16进制整数
for(int i=0;i<bytes.length;i++)
{
sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
}
return sb.toString();
}
/*
* 将16进制数字解码成字符串,适用于所有字符(包括中文)
*/
public static String decode(String bytes)
{
ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);
//将每2位16进制整数组装成一个字节
for(int i=0;i<bytes.length();i+=2)
baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));
return new String(baos.toByteArray());
}
或
String str="中";
char c=(char)str.charAt(0);
System.out.println(c+"转换为16进制为:"+Integer.toString(c,16));
System.out.println("16进制转换为字符串为:"+(char)Integer.valueOf(Integer.toString(c, 16),16).intValue());
public class testcolor {
private static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] {src0})).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] {src1})).byteValue();
byte ret = (byte) (_b0 ^ _b1);
// System.out.println(ret<<8);
return ret;
}
/**
* @param src
* @return
*/
/*private static byte[] HexString2Bytes(String src) {
byte[] ret = new byte[6];
byte[] tmp = src.getBytes();
for (int i = 0; i < 3; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
;*/
public static byte[] HexString2Bytes(String src)
{ byte[] ret = new byte[6];
byte[] tmp = src.getBytes(); for(int i=0; i<6; ++i ){ ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]); } return ret; }
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
String s="ff22ee";
Number ss;
byte[] ret = new byte[6];
Integer i=new Integer(ret[0]);
ret = HexString2Bytes(s) ;
int c=((ret[2]<<8|ret[1]<<8|ret[0])|0xff000000);
//Color cc=new Color(c);
// System.out.println(cc.getRed()+":::"+cc.getBlue()+":::"+cc.getGreen());
}
}
将IP地址转为10进制数,使用小端模式
public static int parseIPNUmber(String ipNumberStr)
throws IllegalArgumentException {
int result = 0;
if (ipNumberStr == null) {
throw new IllegalArgumentException();
}
StringTokenizer tokenizer = new StringTokenizer(ipNumberStr, ".");
try {
String tmp = ipNumberStr;
// get the 3 first numbers
int offset = 0;
for (int i = 0; i < 3; i++) {
// get the position of the first dot
int index = tmp.indexOf(".");
// if there is not a dot then the ip string representation is
// not compliant to the decimal-dotted notation.
if (index != -1) {
// get the number before the dot and convert it into
// an integer.
String numberStr = tmp.substring(0, index);
int number = Integer.parseInt(numberStr);
if ((number < 0) || (number > 255)) {
throw new IllegalArgumentException(ipNumberStr);
}
result += number << offset;
offset += 8;
tmp = tmp.substring(index + 1);
} else {
throw new IllegalArgumentException(ipNumberStr);
}
}
// the remaining part of the string should be the last number.
if (tmp.length() > 0) {
int number = Integer.parseInt(tmp);
if ((number < 0) || (number > 255)) {
throw new IllegalArgumentException(ipNumberStr);
}
result += number << offset;
} else {
throw new IllegalArgumentException(ipNumberStr);
}
}
catch (NoSuchElementException ex) {
throw new IllegalArgumentException(ipNumberStr);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException(ipNumberStr);
}
return result;
}
将10进制数字转为IP地址
public static String toip(int mIPNumber) {
StringBuffer result = new StringBuffer();
int temp;
temp = mIPNumber & 0x000000FF;
result.append(temp);
result.append(".");
temp = (mIPNumber >> 8) & 0x000000FF;
result.append(temp);
result.append(".");
temp = (mIPNumber >> 16) & 0x000000FF;
result.append(temp);
result.append(".");
temp = (mIPNumber >> 24) & 0x000000FF;
result.append(temp);
return result.toString();
}
掩码和网络地址的转换 例如 /24就是255.255.255.0
public static int computeNetworkPrefixFromMask(int mask) {
int result = 0;
int tmp = mask;
while ((tmp & 0x00000001) == 0x00000001) {
result++;
tmp = tmp >>> 1;
}
if (tmp != 0) {
return -1;
}
return result;
}
public static int computeMaskFromNetworkPrefix(int prefix)
{
int subnet = 0;
for (int i = 0; i < prefix; i++) {
subnet = subnet << 1;
subnet += 1;
}
return subnet;
}
例如 System.out.println(toip(computeMaskFromNetworkPrefix(20)));
是255.255.15.0
判断两个IP是不是在一个子网内
public static boolean isIPAddressInRange (int address1,int adress2,int subnet)
{
int result1 = address1 & subnet;
int result2 =adress2 & subnet;
return result1 == result2;
}
读取classes的下面的文件
TestDOMParsing.class.getResourceAsStream("/MSG-response.xml");
返回输入流
web工程不必这样做
使用ServletContext.getResourceAsStream()就可以.
sun的文档这样说得
Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root.
This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file system, in a database, or in a .war file.
简单类型的排序
简单类型不外是byte, char, short, int, long, float, double等数据类型,这些类型不能放在聚集中,只能使用数组。java.util.Arrays方法提供了对这些类型的sort方法(实际上还有很多其他有用的方法),下面是对一个简单的int数组排序:
int[] arr = {2, 3, 1,10,7,4};
System.out.print("before sort: ");
for (int i = 0; i< arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
Arrays.sort(arr);
System.out.print("after sort: ");
for (int i = 0; i< arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
输出结果:
before sort: 2 3 1 10 7 4
after sort: 1 2 3 4 7 10
对象的排序
对象可以放在数组里,同样调用Arrays.sort(Object[] arr)即可;也可以放到聚集里,用java.util.Collections的sort(List list)。注意不是list必须实现List接口而不仅仅是Collection接口。
但是这个类必须实现了java.lang.Comparable接口。这个接口只有一个方法:int compartTo(Object o),当本对象比传入的对象大时,返回一个正整数。 以类Programmer为例:
class Programmer implements Comparable{
private String name;
private String language;
private double pay;
public Programmer(String name, String language, double pay) {
this.name = name;
this.language = language;
this.pay = pay;
}
public int compareTo(Object o) {
Programmer other = (Programmer)o;
return (int)pay - (int)other.pay;
}
public String toString(){
return "{name: " + name + ", language: " + language + ", money: " + pay + "}";
}
}
对其进行排序:
ArrayList list = new ArrayList();
list.add(new Programmer("张三", "C", 12000));
list.add(new Programmer("李四", "Java", 200));
list.add(new Programmer("王五", "C++", 5000));
list.add(new Programmer("钱六", "VB", 3000));
System.out.println("before sort: " + list);
Collections.sort(list);
System.out.println("after sort: " + list);
输出:
before sort: [{name: 张三, language: C, money: 12000.0}, {name: 李四, language: Java, money: 200.0}, {name: 王五, language: C++, money: 5000.0}, {name: 钱六, language: VB, money: 3000.0}]
after sort: [{name: 李四, language: Java, money: 200.0}, {name: 钱六, language: VB, money: 3000.0}, {name: 王五, language: C++, money: 5000.0}, {name: 张三, language: C, money: 12000.0}]