开发者

How to split an int

I want to read in an int. For example 001. After I want to cut up the into so that A = 0, B = 0 and C = 1. I want to开发者_如何学C do this in C. Thanks!


If 001 is a bit representation of your integer value I, then:

int A = (I >> 2) & 0x1
int B = (I >> 1) & 0x1
int C = I & 0x1


You can achieve the result wanted by using modulus operator (%) and integer division (/). It's easier to understand than bitwise operators when you're starting to learn C.

scanf("%d", &i);    
a = i / 100;
b = (i % 100) / 10;
c = (i % 100) % 10;


Building on Karl Bielefeldt's comment:

You can create a union of a char and a bitfield such as:

typedef union
{
    unsigned char byte;
    unsigned char b0 : 1;
    unsigned char b1 : 1;
    unsigned char b2 : 1;
    unsigned char b3 : 1;
    unsigned char b4 : 1;
    unsigned char b5 : 1;
    unsigned char b6 : 1;
    unsigned char b7 : 1;
}TYPE_BYTE;

TYPE_BYTE sample_byte;

...then assign a value to sample_byte.byte and access each individual bit as sample_byte.b0, sample_byte.b1, etc. The order in which the bits are assigned is implementation dependent--read your compiler manual to see how it implements bitfields.

Bitfields can also be created with larger int types.


Edit (2011-03-15):

Assuming that maybe you want to read in a 3-digit base-10 integer and split the three digits into three variables, here's some code that should do that. It hasn't been tested so you might need to do some tweaking:


void split_base10(const unsigned int input, unsigned int *a, unsigned int *b, unsigned int *c)
{
    unsigned int x = input;

    *c = x%10;
    x /= 10;
    *b = x%10;
    *a = x/10;
}

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜