6 - OperatorExamples, BitWise Operators
6 - OperatorExamples, BitWise Operators
Decimal to Binary
Why?? Because if you would have considered 16 bits then answer would have been different !!
And if you would have considered 32 bits then answer would have been different !!
So what would the answer be??
Bitwise Not in this case gives you a negative number actually 11111101
See in 11111101, Most significant bit is 1, that means a negative number.
So to know the answer, keep the MSB intact and reverse all other bits à you
get 10000010
Solution:
Here 0xCAFE means hexadecimal number CAFÉ.
(In Hexadecimal number system, 0-9 are represented as such and 10 is represented as
A, 11 as B, 12 as C, 13 as D, 14 as E, 15 as F
If our input number i.e CAFÉ falls into any of these cases, then the test
condition will be satisfied.
But our number contains 8 other bits also apart from last four, so we need to
make them 0 so that we are left with the last 4 bits only to compare. So we
first take bitwise and (&) of 0xCAFE with 0xF (0x000F)
Now we are only left with last 4 bits, we can easily check these if they fall into any of the 5 cases
using if condition
Consider int val=0xCAFE; Write expressions using bitwise operators
that do the following:
test if atleast three of last four bits (LSB) are on
val=0xCAFE;
bits=val & 0xF;
else:
print("atleast three of last four bits are not on");
Consider val=0xCAFE; Write expressions using bitwise operators that
do the following:
1) test if atleast three of last four bits (LSB) are on
2) reverse the byte order (i.e., produce val=0xFECA)
3) rotate four bits (i.e., produce val=0xECAF)
Here we have taken & of our input number 0xCAFE (which was put in val variable) with
0xFF why are we taking this AND? Because if we directly apply
1100 1010 1111 1110 CAFE left or right shift in input number, some bits will become 0
0000 0000 1111 1111 & and actual value will be tampered
0000 0000 1111 1110
Now apply left shift by 8 positions (<<8) in this resulting bits. You will get --
1111 1110 0000 0000 ----------(1)
ECAF
In-Built functions
hex()
oct()
[ord(c) for c in "CAFE"] #to get the ASCII values
output: [67, 65, 70, 69]
chr(67)
output: “C”
(0xCAFE).bit_length()
Output: 16