java中String类型的如何转为byte[]

如题,谢谢

一、String转byte数组简单版:

1、String str = "abcd";

2、byte[] bs = str.getBytes();

二、复杂版

// pros - no need to handle UnsupportedEncodingException // pros - bytes in specified

encoding scheme byte[] utf8 = "abcdefgh".getBytes(StandardCharsets.UTF_8); 

System.out.println("length of byte array in UTF-8 : " + utf8.length);

System.out.println("contents of byte array in UTF-8: " + Arrays.toString(utf8)); 

Output : length of byte array in UTF-8 : 8 contents of byte array in UTF-8: [97, 98, 99, 100, 101, 102, 103, 104]1

扩展资料:

反过来,将Byte数组转化为String的方法

using System; 

using System.Text; 

public static string FromASCIIByteArray(byte[] characters) 

ASCIIEncoding encoding = new ASCIIEncoding( ); 

string constructedString = encoding.GetString(characters); 

return (constructedString); 


·

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2019-09-08

调用String类的getBytes()方法:

public static byte[] strToByteArray(String str) {    

if (str == null) {       

return null;
   

}   

byte[] byteArray = str.getBytes();    

return byteArray;
}

扩展资料:

getBytes() 是Java编程语言中将一个字符串转化为一个字节数组byte[]的方法。String的getBytes()方法是得到一个系统默认的编码格式的字节数组。

存储字符数据时(字符串就是字符数据),会先进行查表,然后将查询的结果写入设备,读取时也是先查表,把查到的内容打印到显示设备上,getBytes()是使用默认的字符集进行转换,getBytes(“utf-8”)是使用UTF-8编码表进行转换。

getBytes() 方法有两种形式:

getBytes(String charsetName): 使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

getBytes(): 使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

参考资料:getBytes()-百度百科

本回答被网友采纳
第2个回答  2008-08-12
你是说有数字字符组成的字符串变成自己型数组是吗?
比如 "123456" > byte[]={1,2,3,4,5,6}
第3个回答  2008-08-12
这种问题就属于知道了就及其简单,不知道就够你忙活半天的那种。其实只要一个语句就OK了:

byte[] byteArray = System.Text.Encoding.Default.GetBytes( str );
怎么样,够简单吧?
第4个回答  推荐于2017-11-29
楼上的确定使用的是java?

String s = "fs123fdsa";//String变量

byte b[] = s.getBytes();//String转换为byte[]

String t = new String(b);//bytep[]转换为String本回答被提问者采纳
相似回答