summaryrefslogtreecommitdiff
path: root/2/homework/bytes_structure_2.71.c
diff options
context:
space:
mode:
authorMike Vink <mike@pionative.com>2024-05-22 08:49:29 +0200
committerMike Vink <mike@pionative.com>2024-05-22 08:49:29 +0200
commit51169f5f9ab178a4ddfe9dac461405a71c9c0f94 (patch)
tree0b6bb0c6c31ee27361b28e2c5993f362c1cc95e2 /2/homework/bytes_structure_2.71.c
parent77f19e4a89d8dec97930c5e237139734c5fb3365 (diff)
organise
Diffstat (limited to '2/homework/bytes_structure_2.71.c')
-rw-r--r--2/homework/bytes_structure_2.71.c67
1 files changed, 67 insertions, 0 deletions
diff --git a/2/homework/bytes_structure_2.71.c b/2/homework/bytes_structure_2.71.c
new file mode 100644
index 0000000..61ead1c
--- /dev/null
+++ b/2/homework/bytes_structure_2.71.c
@@ -0,0 +1,67 @@
+#include <stdio.h>
+#include <string.h>
+
+typedef unsigned packed_t;
+
+/*
+ 3 2 1 0
+ byte byte byte byte
+ 1000 1100 1110 1111
+ xbyte(..., 2);
+ >> 8
+ 0000 0000 1000 1100
+ & 0xFF
+ 0000 0000 0000 1100
+
+ 0 <= x < 7 -> id
+ -8 < x < 0 -> minus
+*/
+int xbyte(packed_t word, int bytenume);
+int xbyte(packed_t word, int bytenum) {
+ int max_bytes = 3;
+ int max_bits = max_bytes << 3;
+ int shift_bits = (3 - bytenum) << 3;
+ return (int) word << shift_bits >> max_bits;
+}
+
+/*
+ Copy integer into buffer if space is available
+ WARNING: The following code is buggy
+
+ size_t is an unsigned. So one of the operands gets casted.
+ Either
+ int -> unsigned
+ or
+ unsigned -> int
+
+ apparently the result of unsigned - int or int - unsigned -> unsigned
+ */
+void buggy_copy_int(int val, void *buf, int maxbytes) {
+ /*
+ Check if maxbytes will cause problems when converted to unsigned.
+ */
+ if (maxbytes < 0) {
+ return;
+ }
+ if (maxbytes >= sizeof(val)) {
+ memcpy(buf, (void *) &val, sizeof(val));
+ }
+}
+
+int main() {
+ int maxbytes = 4;
+ char buf[maxbytes];
+ int i;
+ for (i=0; i<maxbytes; ++i) {
+ buf[i] = 'a';
+ }
+
+ buggy_copy_int(32, buf, maxbytes);
+ for (i=0; i<maxbytes; ++i) {
+ printf("%x\n", buf[i]);
+ }
+ return 0;
+
+ printf("%x\n", xbyte(0x0000FF00, 1));
+ return 0;
+}