In a Military database system, IDs of the army personnel are stored in a 32-bit value
which is coded as follows:
a. 7-bits Belt number
b. 10-bits Batch number
c. 5-bits Log number
d. 10-bits Unit number
Your Task is to write a C++ Program which inputs a four-byte integer ID, and a string Name of the
army man. Your Program will separate the Belt number, Batch number, Log number and Unit
number and prints the information in the following manner.
Enter Name of Army Man Khan
Enter ID of Army Man: 858993459
Belt number of Khan is : 51
Batch number of Khan is: 614
Log number of Khan is: 25
Unit number of Khan is: 204
can anyone solve or give a hint how to do this
bitfield will do all the work for you. it may be good practice, or the intent, to do it 'by hand'.
to do it by hand, take your unsigned 32 bit value and shift (>>) it down until you have just the belt number. extract the belt number. Now zero out the top 7 bits, which you can do with &. That is, number & 000000011111111111111...etc (binary) but use a hex or decimal constant once you work out what the value is (calc in windows understand binary..).
beware of 'endian' issues; make sure you are poking at the correct bits.
anyway, once you zero out the top 7 bits, you can shift it again to get the next group, repeat the same idea (different constants each go though) until you pulled off all the values.
basically, you really need to understand binary numbers, the shift, and, or, not, xor bit-wise logic operators and if you understand those, this will be very easy.
there are more efficient/smarter ways to do this (still not counting bitfield/bitset); the above idea is the most basic brute force way.
bitfield/bitset is the right way to do it, but again, hands on will teach you something.
It may, on certain implementations; and lead to general insanity on others.
The following properties of bit fields are implementation-defined:
Everything about the actual allocation details of bit fields within the class object
. For example, on some platforms, bit fields don't straddle bytes, on others they do
. Also, on some platforms, bit fields are packed left-to-right, on others right-to-left