tags:

views:

91

answers:

2

Hi, I have to retrieve first bit from 1 byte. For this i stored whole 1 byte in unsigned char Array. Now i retrieved first bit as per below code:

unsigned char byteArray[100];
.....
.....//some code to store 1 byte in byte array
//now 1st bit will be:
int bit=(int) byteArray[0];

I just wanted to confirm that step involved in retrieving 1st bit is right or not? Is there any better way to retrieve single bit from unsigned char array(byte array) in C.

A: 

No, the array indexer is going to return data the size of an unsigned char, not a single bit. Use byteArray[0] & 1; - masking the value so that you only get the first bit (depending on which end is the "first"). The other end would be & 128.

Eric Mickelsen
+1 for handling endianess.
alam
james
@all I am sorry. I have a query endianess is storing of a word staring from lower address or higher address. In this case how it is going to effect my first bit?
alam
@Goutham: No, I'm pretty sure the most significant bit in an unsigned char is worth 128. You need the entire byte to get to 255.
Eric Mickelsen
@james: byteArray[0] is the first *byte*. byteArray[7] is the 8th *byte*. I think you're misunderstanding how arrays and indexers work.
Eric Mickelsen
@alam Endianness does not effect the way bits are stored. A Byte should always be looked at as one unit of data. Endianness only effects ordering of bytes.
Goutham
@Eric Mickelsen - I'm Sorry about 128, you're right.
Goutham
@Goutham: Even though it may not be significant in this context, theoretically, bit-order is a possible form of endianness. The real issue is what james meant by "first."
Eric Mickelsen
+1  A: 

How (and why) do you store a byte in a byte array for this purpose? Its not necessary.

In any case, if you want to retrieve the first bit of a byte, all you have to do is one bit operation.

unsigned char byte = <some random value>;  // your byte containing the value.
unsigned int first_bit = byte & 1;  // for Least significant bit

The operation byte & 1 is a bitwise AND operation.

Goutham