Hi,

I would use something like:

for (i=0; i<4; i++)
  char_counter[i] = ((unsigned char*)&long_counter)[i];

for (i=0; i<4; i++)
  ((unsigned char*)&long_counter)[i] =
char_counter[i];

Hynek



Dne 4.5.2011 4:08, stoffer@skulp.net napsal(a):
Hi, I have to transmit an unsigned long as four bytes, so I split them up
and join them again, but with the folowing example code, I get overflow at
long_counter>32767 - can any of you give me a clue how to do it right?

<http://code.google.com/p/kodak-timer/source/browse/ir_test/four_unsigned_char_to_unsigned_long.c>

unsigned char i;
unsigned long long_counter;
unsigned char char_counter[4];

void main(void) {
	unsigned char len;
	unsigned char lcd_buf[16];

	OSCCONbits.SCS = 0x0;		// System Clock Select bits = External oscillator
	OSCCONbits.IRCF = 0x7;		// Internal Oscillator Frequency Select bits 8
MHz (INTOSC drives clock directly)

	lcd_init();
	while (1) {
		for (long_counter = 0; long_counter < 0xffff0000; long_counter += 50) {
			// split long_counter to four unsigned char's
			for (i = 0; i < 4; i++) {
				char_counter[i] = (long_counter & (0xff << (i * 8))) >> (i * 8);
			}

			// convert them to unsigned int again
			long_counter = char_counter[0] | (char_counter[1] << 8) |
(char_counter[2] << 16) | (char_counter[3] << 24);
			sprintf(lcd_buf, "%lu", long_counter);
			debug(lcd_buf);
		}
	}
}

P.S. Compiling for pic18f2550

- kristoffer ek