devxlogo

Extracting bits.

Extracting bits.

Question:
How do I extract the value from a certain number of bits of an unsigned type?

ex: date is stored as unsigned date = 0x26cf;    bits         meaning    0-4          Day    5-8          Month    9-15         Year (1980-2099)

How do I get the Day, Month and Year?

Answer:
There are two steps to extracting bit values this way. First, you must shift those bits down to the zero bit so that the value starts with 0. Second, you must clear any bits you are not interested in so you are testing the value of only the intended bits.

Use C’s shift operator (>>), and a bitwise AND (&) to clear unwanted bits, to extract the values you want.

nDay = (nDate & 0x1F);nMonth = ((nDate >> 5) & 0xF);nYear = 1980 + ((nDate >> 9) & 0x7F);

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist