diff options
| author | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
|---|---|---|
| committer | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
| commit | 33613a85afc4b1481367fbe92a17ee59c240250b (patch) | |
| tree | 670b842326116b376b505ec2263878912fca97e2 /Master/Reference Architectures and Patterns/hjp5/examples/ByteKit.java | |
| download | Studium-master.tar.gz Studium-master.tar.bz2 | |
Diffstat (limited to 'Master/Reference Architectures and Patterns/hjp5/examples/ByteKit.java')
| -rw-r--r-- | Master/Reference Architectures and Patterns/hjp5/examples/ByteKit.java | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/Master/Reference Architectures and Patterns/hjp5/examples/ByteKit.java b/Master/Reference Architectures and Patterns/hjp5/examples/ByteKit.java new file mode 100644 index 0000000..778a7d8 --- /dev/null +++ b/Master/Reference Architectures and Patterns/hjp5/examples/ByteKit.java @@ -0,0 +1,56 @@ +/**
+ * ByteKit
+ *
+ * Einfache Klasse zur Umwandlung zwischen int, char und
+ * vorzeichenlosen Bytes.
+ */
+public class ByteKit
+{
+ /**
+ * Wandelt value (0 <= value <= 255) in ein byte um.
+ */
+ public static byte fromUnsignedInt(int value)
+ {
+ return (byte)value;
+ }
+
+ /**
+ * Wandelt c in ein byte um. Das High-Byte wird ignoriert.
+ */
+ public static byte fromChar(char c)
+ {
+ return (byte)(c & 0xFF);
+ }
+
+ /**
+ * Betrachtet value als vorzeichenloses byte und wandelt
+ * es in eine Ganzzahl im Bereich 0..255 um.
+ */
+ public static int toUnsignedInt(byte value)
+ {
+ return (value & 0x7F) + (value < 0 ? 128 : 0);
+ }
+
+ /**
+ * Betrachtet value als vorzeichenloses byte und wandelt
+ * es in ein Unicode-Zeichen mit High-Byte 0 um.
+ */
+ public static char toChar(byte value)
+ {
+ return (char)toUnsignedInt(value);
+ }
+
+ /**
+ * Liefert die Binaerdarstellung von value.
+ */
+ public static String toBitString(byte value)
+ {
+ char[] chars = new char[8];
+ int mask = 1;
+ for (int i = 0; i < 8; ++i) {
+ chars[7 - i] = (value & mask) != 0 ? '1' : '0';
+ mask <<= 1;
+ }
+ return new String(chars);
+ }
+}
\ No newline at end of file |
