Skip to content

Instantly share code, notes, and snippets.

@Urpagin
Created November 27, 2025 20:56
Show Gist options
  • Select an option

  • Save Urpagin/e7716904ac355f36fa782dd8d0054b1e to your computer and use it in GitHub Desktop.

Select an option

Save Urpagin/e7716904ac355f36fa782dd8d0054b1e to your computer and use it in GitHub Desktop.
Bitwise shenanigans
#if 0
_TMP="$(mktemp -d)"
clang -Wall -Wextra -pedantic -o "${_TMP}/a.out" "$0"
"${_TMP}/a.out" "$@"
RV=$?
# [, [[ and test are unsuitable on some shell (e.g., dash)
case $_TMP in
'/tmp/'*)
rm -rf "$_TMP"
;;
esac
exit "${RV}"
#endif
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
// Source code author: Urpagin on 2025-11-27.
// Quick & Dirty fiddling in C.
// Inspiration from "Why Some Low-Level Projects Are Full of Weird Code Like This" by CoreDumped on YouTube.
// Sets the nth bit to 1.
// n is comprised between 0 and 7.
// 0 is the least significant bit.
void set(uint8_t* byte, uint8_t n) {
if (n > 7) {
fprintf(stderr, "Error: index too large\n");
return;
}
(*byte) |= (1 << n);
}
// Flips the nth bit.
// n is comprised between 0 and 7.
void toggle(uint8_t* byte, uint8_t n) {
if (n > 7) {
fprintf(stderr, "Error: max n is 7\n");
return;
}
(*byte) ^= (1 << n);
}
// Clears the nth bit.
// n is comprised between 0 and 7.
void clear(uint8_t* byte, uint8_t n) {
if (n > 7) {
fprintf(stderr, "Error: max n is 7\n");
return;
}
(*byte) &= ~(1 << n);
}
// Peeks at the nth bit.
// Returns {0, 1}
int peek(uint8_t byte, uint8_t n) {
if (byte & (1 << n)) return 1;
return 0;
}
// Peeks a whole byte.
void peek_byte(uint8_t byte) {
for (int i = 0; i < 8; ++i)
printf("%d: %d\n", i, peek(byte, i));
}
int main(void) {
printf("[Start Of Program]\n");
uint8_t byte = 0;
printf("byte before: %d\n", byte);
set(&byte, 1);
toggle(&byte, 7);
printf("byte after: %d\n", byte);
// Effectively a no-op on the sixth bit.
set(&byte, 5);
toggle(&byte, 5);
peek_byte(byte);
return 0;
}
@Urpagin
Copy link
Author

Urpagin commented Nov 27, 2025

An fprintf is missing from peek().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment