4
byte abc[]="204.29.207.217";

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

bluish
  • 26,356
  • 27
  • 122
  • 180
Ajay Yadav
  • 1,625
  • 4
  • 19
  • 29
  • possible duplicate of [Convert InputStream to byte\[\] in Java](http://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-in-java) – bmargulies Sep 10 '11 at 19:44

3 Answers3

27

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Will `(byte) 128` result in `-1`? I'm always confused with it. I know it will work in C++ (except we have to use `char` instead of `byte`), but I wasn't sure about Java. – Martijn Courteaux Sep 10 '11 at 11:31
  • 1
    @Martijn: No, `(byte) 128` will result in -128. `(byte) 255` will result in -1. – Jon Skeet Sep 10 '11 at 11:44
  • 1
    @Martijn `byte` is an 8-bit signed integer in Java, it's range goes from -128 to +127. It's stored in [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) format. – Jesper Sep 10 '11 at 14:46
  • Oh, yes indeed! I meant indeed `(byte) 255`. Thanks. – Martijn Courteaux Sep 10 '11 at 16:08
3

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

mre
  • 43,520
  • 33
  • 120
  • 170
2

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

Theo
  • 1,303
  • 12
  • 11