Nur wie zähle ich da denn jetzt hoch ? Das ist ja mit einem mehr oder minder großen Aufwand verbunden wenn ich jedes Byte händisch erhöhe und Überläufe prüfen muss..
Andererseits kann ich einfach einen Integer nehmen, der hat ja 32bit, da ist das Hochzählen kein Problem. Nur wie kriege ich einen Integer in ein 4-byte Array ?
Gibt es da eine einfach Möglichkeit oder muss ich das händisch ausprogrammieren ?
Hallo um kein neues Thema zu erstellen frage ich mal kurz hier nach Hilfe.
Mein code:
Java:
importjava.nio.ByteBuffer;publicclassBefehle{publicstaticvoidmain(String[] args){ByteBuffer b =ByteBuffer.allocate(3);
b.putInt(15);// byte[] result = b.array();System.out.println(b);}}
Console:
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Unknown Source)
at java.nio.HeapByteBuffer.putInt(Unknown Source)
at Befehle.main(Befehle.java:6)
importjava.nio.ByteBuffer;publicclassBefehle{publicstaticvoidmain(String[] args){ByteBuffer b =ByteBuffer.allocate(2);
b.putShort(10);byte[] result = b.array();System.out.println(result);}}
aber wieso funktioniert das nicht?
console: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method putShort(short) in the type ByteBuffer is not applicable for the arguments (int)
importjava.nio.ByteBuffer;publicclassBefehle{publicstaticvoidmain(String[] args){ByteBuffer b =ByteBuffer.allocate(2);
b.putShort(10);byte[] result = b.array();System.out.println(result);}}
aber wieso funktioniert das nicht?
console: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method putShort(short) in the type ByteBuffer is not applicable for the arguments (int)
Auch, wenn es sich erledigt hat, der Vollständigkeit halber die Antworten. Nur für den (unwahrscheinlichen) Fall, dass jemand die Forensuche benutzt :lol:
Die zahl 2 ist doch ein Int und die kann ich doch mit 3 bytes abspeichern?
Eine Variable vom Typ int belegt in Java immer 4 bytes. Auch, wenn man die Zahl 2 in einem byte abspeichern könnte, werden 4 bytes belegt. Es wäre ja immerhin denkbar, dass man der Variable irgendwann einmal eine größere Zahl zuweist.
[JAVA=6]b.putShort(10);[/code]
The method putShort(short) in the type ByteBuffer is not applicable for the arguments (int)
Ganze Zahlen Java-Code sind immer vom Typ int. Wenn man das nicht will, muss man entweder vorher eine Variable des gewünschten Typs deklarieren und initialisieren, oder den Parameter explizit casten:
Eine Variable vom Typ int belegt in Java immer 4 bytes. Auch, wenn man die Zahl 2 in einem byte abspeichern könnte, werden 4 bytes belegt. Es wäre ja immerhin denkbar, dass man der Variable irgendwann einmal eine größere Zahl zuweist.