您的位置:首页 > 编程语言 > Java开发

java 类型转换的一些例子.

2013-11-28 20:24 323 查看
//java中如何将byte数组内容转换为字符串?
import java.util.Arrays;

public class ByteTest
{

/**
* @param args
*/
public static void main(String[] args)
{
String str = "Hello World";

// string 转
byte[] bs = str.getBytes();

System.out.println(Arrays.toString(bs));

// byte转string
String str2 = new String(bs);
System.out.println(str2);
}

}

//字符串转数组的另一种办法.
String str = "9999";
byte[] ary = new byte[str.length()];

for (int i = 0; i < str.length(); i++)
{
ary[i] = (byte) str.charAt(i);
System.out.println(ary[i]);
}

//java中,如何将一个字节数组转换成字符串
byte[] a = { 'a', 'b', 'c', 'd' };
String e = new String(a);
System.out.println(e);

/*在java中如何将全为数字的字符串转化为byte数组,字节数组中元素的值是对应数位的值
*
* 例如将String str=”99999“;转化为byte[]数组,byte[0]=9;byte[1]=9等等
谢谢
byte[0]=9;
byte[1]=9;
byte[2]=9;
不是转化为char什么的才是9
*/

public class ByteTest
{

/**
* @param args
*/
public static void main(String[] args)
{

String s = "99999";
byte[] bytes = s.getBytes();
for (int i = bytes.length - 1; i >= 0; i--)
{
bytes[i] -= (byte) '0';
}
for (int i = 0; i < bytes.length; i++)
{
System.out.print(bytes[i]);
}
System.out.println();
}
}

// “字符串数组” 转 “字符串”,只能通过循环,
String[] str =
{ "abc", "bcd", "def" };
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length; i++)
{
sb.append(str[i]);
}
String s = sb.toString();
System.out.println(s);

//短整型Short类型为字节类型赋值
Short iShort = 100;
byte[] byBuffer = new byte[20];
for (int i = 0; i < byBuffer.length; i++)
{
byBuffer[i] = iShort.byteValue();
}
//字符数组转字符串
char[] bufchar = new char[10];
String strRead = String.copyValueOf(bufchar, 0, bufchar.length);

1、字节数组转换为字符串
byte[] byBuffer = new byte[20];
... ...
String strRead = new String(byBuffer);
strRead = String.copyValueOf(strRead.toCharArray(), 0, byBuffer.length]);
2、字符串转换成字节数组
byte[] byBuffer = new byte[200];
String strInput="abcdefg";
byBuffer= strInput.getBytes();
注意:如果字符串里面含有中文,要特别注意,在android系统下,默认是UTF8编码,一个中文字符相当于3个字节,只有gb2312下一个中文相当于2字节。这种情况下可采取以下办法:
byte[] byBuffer = new byte[200];
String strInput="我是字符串";
byBuffer= strInput.getBytes("gb2312");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: