简体   繁体   中英

How to assign a value to byte array

byte abc[]="204.29.207.217";

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

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 , eg

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.)

That's a string literal . If you're looking to get the binary representation of the string, use one of the String.getBytes methods.

Either use char[] or String. Make sure and get the includes for String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM