Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

binary - How do I extract bits from 32 bit number

I have do not have much knowledge of C and im stuck with a problem since one of my colleague is on leave.

I have a 32 bit number and i have to extract bits from it. I did go through a few threads but im still not clear how to do so. I would be highly obliged if someone can help me.

Here is an example of what i need to do:

Assume hex number= 0xD7448EAB. In binary= 1101 0111 0100 0100 1000 1110 1010 1011 I need to extract 16 bits, and output that value. I want bits 10 through 25.

The lower 10 bits (Decimal) are ignored. i.e.,10 1010 1011 are ignored.
And the upper 6 bits (Overflow) are ignored. i.e., 1101 01 are ignored.

The remaining 16 bits of data needs to be the output which is 11 0100 0100 1000(numbers in italics are needed as the output).

This was an example but i will keep getting different hex numbers all the time and i need to extract the same bits as i explained.

How do i solve this?

Thank you.

For this example you would output 1101 0001 0010 0011, which is 0xD123, or 53,539 decimal.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK, here's how I wrote it:

#include <stdint.h>
#include <stdio.h>

main() {
    uint32_t in = 0xd7448eab;
    uint16_t out = 0;

    out = in >> 10; // Shift right 10 bits
    out &= 0xffff;  // Only lower 16 bits
    printf("%x
",out);
}

The in >> 10 shifts the number right 10 bits; the & 0xffff discards all bits except the lower 16 bits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...