开发者

C Read char as binary

This is actually part of a project I'm working on using an avr. I'm interfacing via twi with a DS1307 real-time clock IC. It reports information back as a series of 8 chars. It returns in the format:

// Second : ds1307[0]
// Minute : ds1307[1]
// Hour   : ds1307[2]
// Day    : ds1307[3]
// Date   : ds1307[4]
// Month  : ds1307[5]
// Year   : ds1307[6]

What I would like to do is take each part of the time and read it bit by bit. I can't think of a way to do this. Basically lighting up an led if the bit is a 1, but not if it's a 0.

I'd imagine that there is a rather simple way to do it by bitshifting, but I can't put my finger on开发者_StackOverflow the logic to do it.


Checking whether the bit N is set can be done with a simple expression like:

(bitmap & (0x1 << N)) != 0

where bitmap is the integer value (e.g. 64 bit in your case) containing the bits.

Finding the seconds:

(bitmap & 0xFF)

Finding the minute:

(bitmap & 0xFF00) >> 8

Finding the hour:

(bitmap & 0xFF0000) >> 16


If I'm interpreting you correctly, the following iterates over all the bits from lowest to highest. That is, the 8 bits of Seconds, followed by the 8 bits of Minutes, etc.

unsigned char i, j;
for (i = 0; i < sizeof(ds1307); i++)
{
  unsigned char value = ds1307[i];  // seconds, minutes, hours etc
  for (j = 0; j < 8; j++)
  {
    if (value & 0x01)
    {
      // bit is 1
    }
    else
    {
      // bit is 0
    }
    value >>= 1;
  }
}


Yes - you can use >> to shift the bits right by one, and & 1 to obtain the value of the least significant bit:

unsigned char ds1307[7];
int i, j;

for (i = 0; i < 7; i++)
    for (j = 0; j < 8; j++)
        printf("byte %d, bit %d = %u\n", i, j, (ds1307[i] >> j) & 1U);

(This will examine the bits from least to most significant. By the way, your example array only has 7 bytes, not 8...)


essentially, if the 6 LEDs to show the seconds in binary format are connected to PORTA2-PORTA7, you can PORTA = ds1307[0] to have the seconds automatically lit up correctly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜