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
, 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.)
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.
精彩评论