Topic: byte与String 之间转换的问题

  Print this page

1.byte与String 之间转换的问题 Copy to clipboard
Posted by: orangeyxj
Posted on: 2005-03-27 21:02

有这么几句代码:
String s="abc";
byte[] b=s.getBytes();
System.out.println(b.toString());
打印出来的是一堆乱七八糟的东西,为什么呢?该怎样才能正确转换呢?

先谢谢了

2.Re:byte与String 之间转换的问题 [Re: orangeyxj] Copy to clipboard
Posted by: zyxxyz0001
Posted on: 2005-03-28 00:44

String s = "abc";
byte b[] = s.getBytes();
for (int i = 0; i <= b.length - 1; i++) {
System.out.print(b[i] + " ");
}

3.Re:byte与String 之间转换的问题 [Re: orangeyxj] Copy to clipboard
Posted by: orangeyxj
Posted on: 2005-03-28 02:01

to zyxxyz
谢谢,不过 这样打出来的是97、98、99,不是我想要的"abc",上面我没说清楚,我是想先把“abc”转成byte,然后再转回"abc",也就是说来回做一个循环,主要是想看看如何转换,中间有没有什么要注意的东西

4.Re:byte与String 之间转换的问题 [Re: orangeyxj] Copy to clipboard
Posted by: zaowei21
Posted on: 2005-03-28 08:27

顶一下。不容易打出来吧。

5.Re:byte与String 之间转换的问题 [Re: orangeyxj] Copy to clipboard
Posted by: why
Posted on: 2005-03-28 11:35

orangeyxj wrote:
to zyxxyz
谢谢,不过 这样打出来的是97、98、99,不是我想要的"abc",上面我没说清楚,我是想先把“abc”转成byte,然后再转回"abc",也就是说来回做一个循环,主要是想看看如何转换,中间有没有什么要注意的东西

System.out.println(new String(b));

see http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#String(byte[])

I am not sure whether this's what you want but please keep in mind that the behavior pf getBytes() depends on the charset.

see http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#getBytes()
public byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

Returns:
The resultant byte array

6.Re:byte与String 之间转换的问题 [Re: orangeyxj] Copy to clipboard
Posted by: orangeyxj
Posted on: 2005-03-29 00:07

谢谢各位,谢谢why,我去看文档了,不过全英文,好吃力啊,5555


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923