Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetBytes() returns negative number

Tags:

java

string

*"Hätten Hüte ein ä im Namen, wären sie möglicherweise keine Hüte mehr, sondern Häte."
 72  -61  -92  116  116  101  ...*

GetBytes() returns negative number (-61, () ) at the char 'ä'.

How to get the normal ascii value?

like image 528
user2147674 Avatar asked Mar 22 '14 08:03

user2147674


People also ask

What does getBytes return?

Here, string is an object of the String class. The getBytes() method returns a byte array.

What does negative byte mean?

Negative numbers are stored by decrementing from zero, thus -1 value is always 2(N)-1. The lowest negative number that can be represented is -2(N-1). For the byte case we have 8 bits, even though unsigned values for a byte range from zero up to 255, in Java it's regarded as signed, thus they range from -128 up to 127.

What does getBytes do in Java?

getbytes() function in java is used to convert a string into a sequence of bytes and returns an array of bytes.

Can Java bytes be negative?

In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 .


1 Answers

GetBytes() returns negative number (-61, () ) at the char 'ä'.

Well getBytes() is going to use the platform default encoding, unless you specify an encoding, which you should. I would recommend UTF-8 normally. For example, in Java 7:

byte[] data = text.getBytes(StandardCharsets.UTF_8);

byte in Java is unfortunately signed - but you can think of it as being just 8 bits. If you want to see the effective unsigned, just use:

int unsigned = someByte & 0xff;

How to get the normal ascii value?

That character doesn't exist in ASCII. All ASCII characters are in the range U+0000 to U+007F.

like image 172
Jon Skeet Avatar answered Oct 04 '22 02:10

Jon Skeet