2

Why does Java allow byte arrays to contain negative values such as

byte[] array = new byte[-90, -23, 118, 23, 3, 0, 0, 23, 39]

but Python does not?

  • 2
    JAva bytes are always signed. – Thorbjørn Ravn Andersen Feb 25 '21 at 16:48
  • @akuzminykh Ah, makes sense! But how can Java byte[] contain these values? –  Feb 25 '21 at 16:50
  • @akuzminykh I understand, but why doesn't Python let me do this then: array = bytearrau([-90, -23, 118, 23, etc...]) ? –  Feb 25 '21 at 16:53
  • 1
    It's simply a different way of using 8 bits. In Java a `byte` is signed and ranges from -128 to 127. But you can also use 8 bits to represent a range from 0 to 255. That's useful e.g. when you work with encodings or when you want to represent color. This Python function is probably meant for that. – akuzminykh Feb 25 '21 at 16:57
  • 2
    python array module accepts signed int `array.array('b', [-90, -23, 118, 23, 3, 0, 0, 23, 39])`, its work – Willian Vieira Feb 25 '21 at 16:58
  • @WillianVieira Thank you! –  Feb 25 '21 at 17:00
  • 1
    It depends on how you view the 8 bits in a byte. Java has chosen a completely brain dead and useless view (probably to be consistent with int and long which _are_ useful), which frequently confuses beginners. – Thorbjørn Ravn Andersen Feb 25 '21 at 18:12

0 Answers0