You're viewing a comment by Jens Bauer and its responses.

July 31, 2010, 00:36

Two minor things I've used a few times on my Atari ST, when I needed to count through a mask, leaving some bits as they were:
-This is a simple version:

Count up:

  count = ((count | ~mask) + 1) & mask;

Count down:

  count = ((count - 1) & mask);

You may find it useful for microcontrollers and output ports (welll... actually also mixed ports where some of the pins are inputs).

Sherif - Your 'exchange' is great. I'd prefer using it directly without function call, to eliminate the pointer stuff and the overhead of call/ret.
Someone once said to me: "you can't write a CRC calculation routine in C without a temp variable". The exchange above would make it possible.

I've used something similar...

c = *s++;
if(13 == c || 10 == c)  // if end of line
{
  if((c ^ 13 ^ 10) == s[0]) // if oposite character is following; eg CR/LF or LF/CR
  {
    s++; // skip that char
  }
}

To convert a digit to a binary number:

if('1' == (c | 1)){ digit = c & 1; }

octal...

if('7' == (c | 7)){ digit = c & 7 }

Oh, and instead of doing for instance...

swich_is_on = (PORTA & (1 << PA3)) ? 1 : 0;

Why not use..

switch_is_on = (PORTA >> PA3) & 1;

To detect a carry, when you don't have the carry bit available:

uint8_t a;
uint8_t b;
uint8_t prev_a;
a = (any value);
b = (any value);

prev_a = a;
a = a + b;
carry = a < prev_a;

This works because b can be max. 255. A can be max. 255. (255+255) & 255 = 254, which is smaller than the previous value.

Same thing for subtracting; just check for a > prev_a than, instead of a < prev_a.

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "lcd_143": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.