I have a byte array like this: (this is not the actual byte array, I have modified it)
[69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98]
I want to know how can I initialize this in Java so that I can convert this byte array to String? Below line doesn't work.
// this doesn't work
byte[] bytes = [69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98];
// now convert to string
String data = new String(bytes, StandardCharsets.UTF_8);
asked Sep 18, 2015 at 23:50
user1950349
5,23620 gold badges74 silver badges130 bronze badges
-
possible duplicate of How do I initialize a byte array in Java?Jorgesys– Jorgesys2015年09月18日 23:52:25 +00:00Commented Sep 18, 2015 at 23:52
-
nobody expected signed bytes:) instead of 255, you need to write -1, etc.ZhongYu– ZhongYu2015年09月19日 02:10:50 +00:00Commented Sep 19, 2015 at 2:10
1 Answer 1
This should work
byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};
Byte can hold upto -128 to 127 only. Some of the values are exceeding the limit of a byte value. So you need to cast them to byte.
answered Sep 18, 2015 at 23:51
Suresh Atta
122k38 gold badges207 silver badges315 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Mick Mnemonic
This is probably not what the OP wants. It seems that the intention is to create a string based on the unicode values of different characters.
Suresh Atta
@MickMnemonic Yes. In OP code, the string conversion works, where he failed to initialize the byte array :)
lang-java