highlander141
highlander141

Reputation: 1725

Reading Structures (Struct information) in C

My question is a bit strange. I've given a Client-Server application, where in Client a Structure has been designed and it contains a Character array with size char values[1000]. I will receive 1000 bits from Server in terms of 0's and 1's. In that I would like to read the bit from 885 and 886's position. How to execute this properly? Coz am getting strange characters when I read at that positions. I think it's because the bits are stored as mass data inside that values[] array like values[1000]={111010101....1}and not like normal array-> int abc[2] = {1,2};.

Is this the reason? Then how can I read 885 and 886's positions from values[1000]={111010101....1}?

Kindly clarify...

Upvotes: 1

Views: 129

Answers (3)

user2045557
user2045557

Reputation:

Assuming that you store 8 bits per single char, it can be done this way. Its the way we use PIN register in ARM.

int bitState = 0;
char buff[1000];

//Some execution that updates the buff

bitState = ((buff & (1 << 885)) ? 1 : 0);
if(bitState)
  //DO this;
else
  //DO that;

bitState = ((buff & (1 << 886)) ? 1 : 0);
if(bitState)
  //DO this;
else
  //DO that;

Upvotes: 1

unwind
unwind

Reputation: 399833

There seems to be a lot of confusion here.

Assuming 8-bit chars just to keep the confusion down, bits 885 and 886 will be in character 110 (counting from 0, that's the 81st character).

If we index the bits from the LSB as bit 0, then that character has these bits in it:

       88888888
bit nr 88888888
       76543210
        **

Reading vertically, we find 885 and 886 where indicated with asterisks (*).

So, to extract these two bits:

const int bit885 = (values[110] & 0x20) >> 5;
const int bit886 = (values[110] & 0x40) >> 6;

Upvotes: 4

LostBoy
LostBoy

Reputation: 958

Your char array contains 8 bits on each position as a char takes up one byte. I suppose that you receive a byte stream from the server? This means that each position takes up 8 bits and you will have to find the correct position by division, e.g.:

char c = values[885/8];

After this still have to shift or mask the correct bit in those 8 bits. You could find the bit position by modulo division: 885 % 8

Read up on bits and bytes and bit operations (and, or, shift)

Also check out how your data is received on the server and how many bytes you receiv

Upvotes: 2

Related Questions