Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value to byte array

Tags:

java

bytearray

byte abc[]="204.29.207.217";

This is giving an error. Please, tell me correct the method.

like image 704
Ajay Yadav Avatar asked Nov 28 '22 06:11

Ajay Yadav


1 Answers

If you're trying to assign hard-coded values, you can use:

byte[] bytes = { (byte) 204, 29, (byte) 207, (byte) 217 };

Note the cast because Java bytes are signed - the cast here will basically force the overflow to a negative value, which is probably what you want.

If you're actually trying to parse a string, you need to do that - split the string into parts and parse each one.

If you're trying to convert a string into its binary representation under some particular encoding, you should use String.getBytes, e.g.

byte[] abc = "204.29.207.217".getBytes("UTF-8");

(Note that conventionally the [] is put as part of the type of the variable, not after the variable name. While the latter is allowed, it's discouraged as a matter of style.)

like image 130
Jon Skeet Avatar answered Dec 04 '22 00:12

Jon Skeet