String getBytes()

E

eeh

Hi,

How to make b[0] to get 0xaa?

String s=""+(char)0xaa;
byte[] b=s.getBytes();
System.out.println(b[0]);<==result is not 0xaa

Thanks!
 
K

Knute Johnson

eeh said:
Hi,

How to make b[0] to get 0xaa?

String s=""+(char)0xaa;
byte[] b=s.getBytes();
System.out.println(b[0]);<==result is not 0xaa

Thanks!

String str = "\u00aa";
 
T

Tom Hawtin

eeh said:
How to make b[0] to get 0xaa?

String s=""+(char)0xaa;
byte[] b=s.getBytes();
System.out.println(b[0]);<==result is not 0xaa

You seem to be confused between chars and bytes.

From API docs to String.getBytes:

"Encodes this String into a sequence of bytes using the platform's
default charset..."

What's the platform default charset? Anyone's guess. It's an utterly
pointless method. Always use a version with of the method that takes an
explicit charset. But what you usually want to do is to stick with chars:

String str = Character.toString((char)0xaa);
char[] cs = str.toCharArray();
System.out.println((int)cs[0]);

Tom Hawtin
 
L

Lothar Kimmeringer

eeh said:
String s=""+(char)0xaa;
byte[] b=s.getBytes();

Try s.getBytes("8859_1"); instead
System.out.println(b[0]);<==result is not 0xaa

Then it should.

Dependent on your original problem, this might still not
be the solution of what you intend to solve.


Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
questions!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top