I'm trying to wrap my head around bitwise operators by tackling some specific problems. An interesting one I got is to first store several numbers into a single variable, then write those numbers back out. The thing stored is a date consisting of, obviously, a day number, month number and year number.
I declared a variable as Integer, because 32 bits is the smallest variable size that enough bits to store one value from 1 to 12, one value from 1 to 31 and one value from 1 to 9999.
Next, I take an input from the console for the "day" part of the Integer variable and assign it to said variable. After that, I shift the bits 4 places to the left which leaves me with 4 free bits on the right to store the "month" part. I then take an input from the console for the month value and assign to my variable the value of (variable OR console_input). After that, I shift everything 14 places to the right to allow a 1 to 9999 value for the year and do another OR operation to assign the value to the 14 bits freed up by the shift.
After which I output to the console the values by shifting back to the right the required amount of time in respect to the part of the date I'm outputting and then AND it with the required number to flip everything left of the leftmost bit of the part to 0 and with that get the values inputted for day, month, and year.
I'm sorry if I wasn't being too clear in my description, but you'll hopefully get what I'm saying by looking at the attached code. The issue I'm having is that the day and month values display correctly, but I always get the wrong year back, and I simply can't understand why. Any help is much appreciated!
Dim inputDate As Integer
Console.WriteLine("Day: ")
inputDate = Console.ReadLine()
inputDate = (inputDate << 4)
Console.WriteLine("Month: ")
inputDate = (inputDate Or Console.ReadLine())
inputDate = (inputDate << 14)
Console.WriteLine("Year: ")
inputDate = (inputDate Or Console.ReadLine())
Console.WriteLine("Day: {0}. Month: {1}. Year: {2}", ((inputDate >> 18) And 31), ((inputDate >> 14) And 15), (inputDate And 9999))
I believe your issue lies on your last line.
You're masking your Day
and Month
with values that produce all 1
's in binary.
However, you're not masking your year correctly.
9,999 is 10 0111 0000 1111
in binary, which means that you're guaranteeing that certain bits will remain 0
when AND
ed together.
This will cause the year to produce flawed results. If you're looking for a 14-bit year format, you need to mask with 2^14 - 1
, which is 16,383
, which is 11 1111 1111 1111
in binary.
Note that 31 and 15 follow the same principles:
15 = 1111
, and 31 = 11111
I hope this helps!