110_bit_manipulation3.zig 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // ----------------------------------------------------------------------------
  2. // Setting, Clearing, and Toggling Bits
  3. // ----------------------------------------------------------------------------
  4. //
  5. // Another exciting thing about Zig is its suitability for embedded
  6. // programming. Your Zig code doesn't have to remain on your laptop. You can
  7. // also deploy your code to microcontrollers! This means you can write Zig to
  8. // drive your next robot or greenhouse climate control system! Ready to enter
  9. // the exciting world of embedded programming? This exercise is designed to
  10. // give you a taste of what it's like to control registers in a
  11. // microcontroller. Let's get started!
  12. //
  13. // A common activity in microcontroller programming is setting and clearing
  14. // bits on input and output pins. This lets you control LEDs, sensors, motors
  15. // and more! In a previous exercise (097_bit_manipulation.zig) you learned how
  16. // to swap two bytes using the ^ (XOR - exclusive or) operator. In this
  17. // exercise, we'll take a closer look at bit manipulation and how we can write
  18. // code that sets and clears specific bits as we would if we were programming
  19. // the pins on a real microcontroller. Included at the end of this exercise are
  20. // some helper functions that demonstrate how we might make our code a little
  21. // more readable.
  22. //
  23. // Below is a pinout diagram for the famous ATmega328 AVR microcontroller used
  24. // as the primary microchip on popular microcontroller platforms like the
  25. // Arduino UNO.
  26. //
  27. // ============ PINOUT DIAGRAM FOR ATMEGA328 MICROCONTROLLER ============
  28. // _____ _____
  29. // | U |
  30. // (RESET) PC6 --| 1 28 |-- PC5
  31. // PD0 --| 2 27 |-- PC4
  32. // PD1 --| 3 26 |-- PC3
  33. // PD2 --| 4 25 |-- PC2
  34. // PD3 --| 5 24 |-- PC1
  35. // PD4 --| 6 23 |-- PC0
  36. // VCC --| 7 22 |-- GND
  37. // GND --| 8 21 |-- AREF
  38. // |-- PB6 --| 9 20 |-- AVCC
  39. // |-- PB7 --| 10 19 |-- PB5 --|
  40. // | PD5 --| 11 18 |-- PB4 --|
  41. // | PD6 --| 12 17 |-- PB3 --|
  42. // | PD7 --| 13 16 |-- PB2 --|
  43. // |-- PB0 --| 14 15 |-- PB1 --|
  44. // | |___________| |
  45. // \_______________________________/
  46. // |
  47. // PORTB
  48. //
  49. // Drawing inspiration from this diagram, we'll use the pins for PORTB as our
  50. // mental model for this exercise in bit manipulation. It should be noted that
  51. // in the following examples we are using ordinary variables, one of which we
  52. // have named PORTB, to simulate modifying the bits of real hardware registers.
  53. // But in actual microcontroller code, PORTB would be defined something like
  54. // this:
  55. // pub const PORTB = @as(*volatile u8, @ptrFromInt(0x25));
  56. //
  57. // This lets the compiler know not to make any optimizations to PORTB so that
  58. // the IO pins are properly mapped to our code.
  59. //
  60. // NOTE : To keep things simple, the following examples are given using type
  61. // u4, so applying the output to PORTB would only affect the lower four pins
  62. // PB0..PB3. Of course, there is nothing to prevent you from swapping the u4
  63. // with a u8 so you can control all 8 of PORTB's IO pins.
  64. const std = @import("std");
  65. const print = std.debug.print;
  66. const testing = std.testing;
  67. pub fn main() !void {
  68. var PORTB: u4 = 0b0000; // only 4 bits wide for simplicity
  69. //
  70. // ------------------------------------------------------------------------
  71. // Setting bits with OR:
  72. // ------------------------------------------------------------------------
  73. // We can set bits on PORTB with the | (OR) operator, like so:
  74. //
  75. // var PORTB: u4 = 0b1001;
  76. // PORTB = PORTB | 0b0010;
  77. // print("PORTB: {b:0>4}\n", .{PORTB}); // output: 1011
  78. //
  79. // -OR op- ---expanded---
  80. // _ Set only this bit.
  81. // /
  82. // 1001 1 0 0 1
  83. // | 0010 0 0 1 0 (bit mask)
  84. // ------ - - - -
  85. // = 1011 1 0 1 1
  86. // \___\_______\
  87. // \
  88. // These bits remain untouched because OR-ing with
  89. // a 0 effects no change.
  90. //
  91. // ------------------------------------------------------------------------
  92. // To create a bit mask like 0b0010 used above:
  93. //
  94. // 1. First, shift the value 1 over one place with the bitwise << (shift
  95. // left) operator as indicated below:
  96. // 1 << 0 -> 0001
  97. // 1 << 1 -> 0010 <-- Shift 1 one place to the left
  98. // 1 << 2 -> 0100
  99. // 1 << 3 -> 1000
  100. //
  101. // This allows us to rewrite the above code like this:
  102. //
  103. // var PORTB: u4 = 0b1001;
  104. // PORTB = PORTB | (1 << 1);
  105. // print("PORTB: {b:0>4}\n", .{PORTB}); // output: 1011
  106. //
  107. // Finally, as in the C language, Zig allows us to use the |= operator, so
  108. // we can rewrite our code again in an even more compact and idiomatic
  109. // form: PORTB |= (1 << 1)
  110. print("Set pins with OR on PORTB\n", .{});
  111. print("-------------------------\n", .{});
  112. PORTB = 0b1001; // reset PORTB
  113. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  114. print("| {b:0>4} // (bitmask)\n", .{0b0100});
  115. PORTB = PORTB ??? (1 << 2); // What's missing here?
  116. checkAnswer(0b1101, PORTB);
  117. newline();
  118. PORTB = 0b1001; // reset PORTB
  119. print(" {b:0>4} // (reset state)\n", .{PORTB});
  120. print("| {b:0>4} // (bitmask)\n", .{0b0100});
  121. PORTB ??? (1 << 2); // What's missing here?
  122. checkAnswer(0b1101, PORTB);
  123. newline();
  124. // ------------------------------------------------------------------------
  125. // Clearing bits with AND and NOT:
  126. // ------------------------------------------------------------------------
  127. // We can clear bits with the & (AND) bitwise operator, like so:
  128. // PORTB = 0b1110; // reset PORTB
  129. // PORTB = PORTB & 0b1011;
  130. // print("PORTB: {b:0>4}\n", .{PORTB}); // output -> 1010
  131. //
  132. // - 0s clear bits when used in conjuction with a bitwise AND.
  133. // - 1s do nothing, thus preserving the original bits.
  134. //
  135. // -AND op- ---expanded---
  136. // __________ Clear only this bit.
  137. // /
  138. // 1110 1 1 1 0
  139. // & 1011 1 0 1 1 (bit mask)
  140. // ------ - - - -
  141. // = 1010 1 0 1 0 <- This bit was already cleared.
  142. // \_______\
  143. // \
  144. // These bits remain untouched because AND-ing with a
  145. // 1 preserves the original bit value whether 0 or 1.
  146. //
  147. // ------------------------------------------------------------------------
  148. // We can use the ~ (NOT) operator to easily create a bit mask like 1011:
  149. //
  150. // 1. First, shift the value 1 over two places with the bit-wise << (shift
  151. // left) operator as indicated below:
  152. // 1 << 0 -> 0001
  153. // 1 << 1 -> 0010
  154. // 1 << 2 -> 0100 <- The 1 has been shifted two places to the left
  155. // 1 << 3 -> 1000
  156. //
  157. // 2. The second step in creating our bit mask is to invert the bits
  158. // ~0100 -> 1011
  159. // we can write this as:
  160. // ~(1 << 2) -> 1011
  161. //
  162. // But if we try to compile ~(1 << 2), we'll get an error:
  163. // unable to perform binary not operation on type 'comptime_int'
  164. //
  165. // Before Zig can invert our bits, it needs to know the number of
  166. // bits it's being asked to invert.
  167. //
  168. // We do this with the @as (cast as) built-in like this:
  169. // @as(u4, 1 << 2) -> 0100
  170. //
  171. // Finally, we can invert our new mask by placing the NOT ~ operator
  172. // before our expression, like this:
  173. // ~@as(u4, 1 << 2) -> 1011
  174. //
  175. // If you are offput by the fact that you can't simply invert bits like
  176. // you can in languages such as C without casting to a particular size
  177. // of integer, you're not alone. However, this is actually another
  178. // instance where Zig is really helpful because it protects you from
  179. // difficult to debug integer overflow bugs that can have you tearing
  180. // your hair out. In the interest of keeping things sane, Zig requires
  181. // you simply to tell it the size of number you are inverting. In the
  182. // words of Andrew Kelley, "If you want to invert the bits of an
  183. // integer, zig has to know how many bits there are."
  184. //
  185. // For more insight into the Zig team's position on why the language
  186. // takes the approach it does with the ~ operator, take a look at
  187. // Andrew's comments on the following github issue:
  188. // https://github.com/ziglang/zig/issues/1382#issuecomment-414459529
  189. //
  190. // Whew, so after all that what we end up with is:
  191. // PORTB = PORTB & ~@as(u4, 1 << 2);
  192. //
  193. // We can shorten this with the &= combined AND and assignment operator,
  194. // which applies the AND operator on PORTB and then reassigns PORTB. Here's
  195. // what that looks like:
  196. // PORTB &= ~@as(u4, 1 << 2);
  197. //
  198. print("Clear pins with AND and NOT on PORTB\n", .{});
  199. print("------------------------------------\n", .{});
  200. PORTB = 0b1110; // reset PORTB
  201. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  202. print("& {b:0>4} // (bitmask)\n", .{0b1011});
  203. PORTB = PORTB & ???@as(u4, 1 << 2); // What character is missing here?
  204. checkAnswer(0b1010, PORTB);
  205. newline();
  206. PORTB = 0b0111; // reset PORTB
  207. print(" {b:0>4} // (reset state)\n", .{PORTB});
  208. print("& {b:0>4} // (bitmask)\n", .{0b1110});
  209. PORTB &= ~(1 << 0); // What's missing here?
  210. checkAnswer(0b0110, PORTB);
  211. newline();
  212. newline();
  213. //
  214. // ------------------------------------------------------------------------
  215. // Toggling bits with XOR:
  216. // ------------------------------------------------------------------------
  217. // XOR stands for "exclusive or". We can toggle bits with the ^ (XOR)
  218. // bitwise operator, like so:
  219. //
  220. //
  221. // In order to output a 1, the logic of an XOR operation requires that the
  222. // two input bits are of different values. Therefore, 0 ^ 1 and 1 ^ 0 will
  223. // both yield a 1 but 0 ^ 0 and 1 ^ 1 will output 0. XOR's unique behavior
  224. // of outputing a 0 when both inputs are 1s is what makes it different from
  225. // the OR operator; it also gives us the ability to toggle bits by putting
  226. // 1s into our bitmask.
  227. //
  228. // - 1s in our bitmask operand, can be thought of as causing the
  229. // corresponding bits in the other operand to flip to the opposite value.
  230. // - 0s cause no change.
  231. //
  232. // The 0s in our bitmask preserve these values
  233. // -XOR op- ---expanded--- in the output.
  234. // _______________/
  235. // / /
  236. // 0110 1 1 0 0
  237. // ^ 1111 0 1 0 1 (bitmask)
  238. // ------ - - - -
  239. // = 1001 1 0 0 1 <- This bit was already cleared.
  240. // \_______\
  241. // \
  242. // We can think of these bits having flipped
  243. // because of the presence of 1s in those columns
  244. // of our bitmask.
  245. print("Toggle pins with XOR on PORTB\n", .{});
  246. print("-----------------------------\n", .{});
  247. PORTB = 0b1100;
  248. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  249. print("^ {b:0>4} // (bitmask)\n", .{0b0101});
  250. PORTB ^= (1 << 1) | (1 << 0); // What's wrong here?
  251. checkAnswer(0b1001, PORTB);
  252. newline();
  253. PORTB = 0b1100;
  254. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  255. print("^ {b:0>4} // (bitmask)\n", .{0b0011});
  256. PORTB ^= (1 << 1) & (1 << 0); // What's wrong here?
  257. checkAnswer(0b1111, PORTB);
  258. // While the examples in this exercise have used only 4-bit wide variables,
  259. // working with 8 bits is no different. Here's a an example where we set
  260. // every other bit beginning with the two's place:
  261. // var PORTD: u8 = 0b0000_0000;
  262. // print("PORTD: {b:0>8}\n", .{PORTD});
  263. // PORTD |= (1 << 1);
  264. // PORTD = setBit(u8, PORTD, 3);
  265. // PORTD |= (1 << 5) | (1 << 7);
  266. // print("PORTD: {b:0>8} // set every other bit\n", .{PORTD});
  267. // PORTD = ~PORTD;
  268. // print("PORTD: {b:0>8} // bits flipped with NOT (~)\n", .{PORTD});
  269. // newline();
  270. //
  271. // // Here we clear every other bit beginning with the two's place.
  272. //
  273. // PORTD = 0b1111_1111;
  274. // print("PORTD: {b:0>8}\n", .{PORTD});
  275. // PORTD &= ~@as(u8, 1 << 1);
  276. // PORTD = clearBit(u8, PORTD, 3);
  277. // PORTD &= ~@as(u8, (1 << 5) | (1 << 7));
  278. // print("PORTD: {b:0>8} // clear every other bit\n", .{PORTD});
  279. // PORTD = ~PORTD;
  280. // print("PORTD: {b:0>8} // bits flipped with NOT (~)\n", .{PORTD});
  281. // newline();
  282. }
  283. // ----------------------------------------------------------------------------
  284. // Here are some helper functions for manipulating bits
  285. // ----------------------------------------------------------------------------
  286. // Functions for setting, clearing, and toggling a single bit
  287. fn setBit(comptime T: type, byte: T, comptime bit_pos: T) !T {
  288. return byte | (1 << bit_pos);
  289. }
  290. test "setBit" {
  291. try testing.expectEqual(setBit(u8, 0b0000_0000, 3), 0b0000_1000);
  292. }
  293. fn clearBit(comptime T: type, byte: T, comptime bit_pos: T) T {
  294. return byte & ~@as(T, (1 << bit_pos));
  295. }
  296. test "clearBit" {
  297. try testing.expectEqual(clearBit(u8, 0b1111_1111, 0), 0b1111_1110);
  298. }
  299. fn toggleBit(comptime T: type, byte: T, comptime bit_pos: T) T {
  300. return byte ^ (1 << bit_pos);
  301. }
  302. test "toggleBit" {
  303. var byte = toggleBit(u8, 0b0000_0000, 0);
  304. try testing.expectEqual(byte, 0b0000_0001);
  305. byte = toggleBit(u8, byte, 0);
  306. try testing.expectEqual(byte, 0b0000_0000);
  307. }
  308. // ----------------------------------------------------------------------------
  309. // Some additional functions for setting, clearing, and toggling multiple bits
  310. // at once with a tuple because, hey, why not?
  311. // ----------------------------------------------------------------------------
  312. //
  313. fn createBitmask(comptime T: type, comptime bits: anytype) !T {
  314. comptime var bitmask: T = 0;
  315. inline for (bits) |bit| {
  316. if (bit >= @bitSizeOf(T)) return error.BitPosTooLarge;
  317. if (bit < 0) return error.BitPosTooSmall;
  318. bitmask |= (1 << bit);
  319. }
  320. return bitmask;
  321. }
  322. test "creating bitmasks from a tuple" {
  323. try testing.expectEqual(createBitmask(u8, .{0}), 0b0000_0001);
  324. try testing.expectEqual(createBitmask(u8, .{1}), 0b0000_0010);
  325. try testing.expectEqual(createBitmask(u8, .{2}), 0b0000_0100);
  326. try testing.expectEqual(createBitmask(u8, .{3}), 0b0000_1000);
  327. //
  328. try testing.expectEqual(createBitmask(u8, .{ 0, 4 }), 0b0001_0001);
  329. try testing.expectEqual(createBitmask(u8, .{ 1, 5 }), 0b0010_0010);
  330. try testing.expectEqual(createBitmask(u8, .{ 2, 6 }), 0b0100_0100);
  331. try testing.expectEqual(createBitmask(u8, .{ 3, 7 }), 0b1000_1000);
  332. try testing.expectError(error.BitPosTooLarge, createBitmask(u4, .{4}));
  333. }
  334. fn setBits(byte: u8, bits: anytype) !u8 {
  335. const bitmask = try createBitmask(u8, bits);
  336. return byte | bitmask;
  337. }
  338. test "setBits" {
  339. try testing.expectEqual(setBits(0b0000_0000, .{0}), 0b0000_0001);
  340. try testing.expectEqual(setBits(0b0000_0000, .{7}), 0b1000_0000);
  341. try testing.expectEqual(setBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  342. try testing.expectEqual(setBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  343. try testing.expectEqual(setBits(0b0000_0000, .{ 2, 3, 4, 5 }), 0b0011_1100);
  344. try testing.expectError(error.BitPosTooLarge, setBits(0b1111_1111, .{8}));
  345. try testing.expectError(error.BitPosTooSmall, setBits(0b1111_1111, .{-1}));
  346. }
  347. fn clearBits(comptime byte: u8, comptime bits: anytype) !u8 {
  348. const bitmask: u8 = try createBitmask(u8, bits);
  349. return byte & ~@as(u8, bitmask);
  350. }
  351. test "clearBits" {
  352. try testing.expectEqual(clearBits(0b1111_1111, .{0}), 0b1111_1110);
  353. try testing.expectEqual(clearBits(0b1111_1111, .{7}), 0b0111_1111);
  354. try testing.expectEqual(clearBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  355. try testing.expectEqual(clearBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  356. try testing.expectEqual(clearBits(0b1111_1111, .{ 0, 1, 6, 7 }), 0b0011_1100);
  357. try testing.expectError(error.BitPosTooLarge, clearBits(0b1111_1111, .{8}));
  358. try testing.expectError(error.BitPosTooSmall, clearBits(0b1111_1111, .{-1}));
  359. }
  360. fn toggleBits(comptime byte: u8, comptime bits: anytype) !u8 {
  361. const bitmask = try createBitmask(u8, bits);
  362. return byte ^ bitmask;
  363. }
  364. test "toggleBits" {
  365. try testing.expectEqual(toggleBits(0b0000_0000, .{0}), 0b0000_0001);
  366. try testing.expectEqual(toggleBits(0b0000_0000, .{7}), 0b1000_0000);
  367. try testing.expectEqual(toggleBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  368. try testing.expectEqual(toggleBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  369. try testing.expectEqual(toggleBits(0b0000_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_0000);
  370. try testing.expectEqual(toggleBits(0b0000_1111, .{ 0, 1, 2, 3 }), 0b0000_0000);
  371. try testing.expectEqual(toggleBits(0b0000_0000, .{ 0, 2, 4, 6 }), 0b0101_0101);
  372. try testing.expectError(error.BitPosTooLarge, toggleBits(0b1111_1111, .{8}));
  373. try testing.expectError(error.BitPosTooSmall, toggleBits(0b1111_1111, .{-1}));
  374. }
  375. // ----------------------------------------------------------------------------
  376. // Utility functions
  377. // ----------------------------------------------------------------------------
  378. fn newline() void {
  379. print("\n", .{});
  380. }
  381. fn checkAnswer(expected: u4, answer: u4) void {
  382. if (expected != answer) {
  383. print("*************************************************************\n", .{});
  384. print("= {b:0>4} <- INCORRECT! THE EXPECTED OUTPUT IS {b:0>4}\n", .{ answer, expected });
  385. print("*************************************************************\n", .{});
  386. } else {
  387. print("= {b:0>4}", .{answer});
  388. }
  389. newline();
  390. }