Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading bits 1

Status
Not open for further replies.

jlynch1

Technical User
Dec 20, 2001
100
0
0
IE
I want to take input from a binary/ascii file in blocks of 128bits and store store the bit in an array which has 128 elements. Put bit 1 in index 0 .....

Then I want to xor the bits . eg the 1st bit in block 1 with the 1st bit in block 2 .....


how would i go about taking in the input in bits and store it in the array.


I would appreciate any help
 
Is your input binary or ASCII?

If it is ASCII

Code:
#define maxbit 128
char oioi[maxbit + 1];
FILE* ascdata = fopen ("filename", "r");
int bit;
oioi[maxbit] = '\0'; /* Set terminator */
fread (oioi, maxbit, 1, ascdata);
/* Convert to binary */
for (bit = 0; bit < maxbit; bit++)
    oioi[bit] &= 1;

If it is binary
Code:
#define maxbit 128
unsigned char raw[maxbit / 8];
char oioi[maxbit + 1];
int byte, bit, relbit;
FILE* rawdata = fopen (&quot;filename&quot;, &quot;rb&quot;);
fread (raw, maxbit / 8, 1, rawdata);
for (bit = 0, byte = 0; bit < maxbit; bit += 8, byte += 1)
{
    for (relbit = 0; relbit < 8; relbit++)
    {
        oioi[relbit + bit] = raw[byte] & 1;
        raw[byte] >>= 1;
    }
}
 
As a more general solution to your problem, you use bitmasks to &quot;get&quot; certain bits.

1 << 0 (which is just 1), 00000001 as a binary byte, corresponds to the first bit.

1 << 1 (i.e. 1 shifted left 1 bit) gives you 00000010 binary, which corresponds to the second bit.

1 << 2 (1 shifted left 2 bits) gives you 00000100 binary, which corresponds to the third bit.

Etc., etc.


To find out whether those bits are set in your data, use the bitwise &.

[tt]char ch;
int x;
// initialize ch

x = ch & ( 1 << 4 );
[/tt]

In this example, x will be 0 if the 5th bit of ch is 0. It will be nonzero if the 5th bit of ch is 1.


Hopefully, that'll help you figure out whatever it is you need to do.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top