This is a walkthrough of how to do the print_bits assignment for the 42 exam.
2.) Then you need to understand bit shifting. It’s a simple concept and Jamie Dawson has a great short tutorial on it here: Basic Bit Shifting Guide
3.) Understanding Bitwise Operators:
I found the Swift guide on bitwise operators to be the best.
https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html
4.) Solving Print Bits
10000000
vs
00101010
It compares all the bits to make a new byte like the Swift tutorial mentions:
If the new byte is non-zero then the ternary statement is true and it prints a 1. Otherwise it prints 0. Then
Assignment name : print_bits
Expected files : print_bits.c
Allowed functions: write
--------------------------------------------------------------------------------
Write a function that takes a byte, and prints it in binary WITHOUT A NEWLINE
AT THE END.
Your function must be declared as follows:
void print_bits(unsigned char octet);
Example, if you pass 2 to print_bits, it will print "00000010"
1.) Make sure you have a good understanding of bits and bytes with the video above.2.) Then you need to understand bit shifting. It’s a simple concept and Jamie Dawson has a great short tutorial on it here: Basic Bit Shifting Guide
3.) Understanding Bitwise Operators:
I found the Swift guide on bitwise operators to be the best.
https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html
4.) Solving Print Bits
// solution
void print_bits(unsigned char octet)
{
int i = 256;
while (i >>= 1)
(octet & i) ? write(1, "1", 1) : write(1, "0", 1);
}
int main(void){
print_bits(42);
return(0);
}
We start i
at 256 so that after the first bit shift i
is equal to 128.i
will then be:10000000
vs
octet
is 42, which in binary is:00101010
It compares all the bits to make a new byte like the Swift tutorial mentions:
If the new byte is non-zero then the ternary statement is true and it prints a 1. Otherwise it prints 0. Then
i
is bit shifted and becomes 01000000 and the while loop checks it again. Doing this with the octet
variable shifting through each of the bits in the byte allows you to print the binary value of octet.
Comments
Post a Comment