Originally Posted by
sonnichs
int long tdelay=6844;
char outbuff[4];
convert_routine(tdelay,outbuff);
Now outbuff must contain: 00 01 0A BC
Are you sure? 6844 when converted to hex is 00 00 1A BC.
Anyway, assuming the values I infer are correct....
Code:
// note: untested code follows; it shows the idea. Use at own risk
void my_possibly_wrong_convert_routine(unsigned long tdelay, unsigned char outbuf[])
{
int i;
for (i = 0; i < 3; ++i)
{
outbuf[3-i] = tdelay % 0x100;
tdelay /= 0x100;
}
}
The magic value here (0x100) is 0xFF + 1 (i.e. 256). All I'm doing is doing repeated remainders and division by 256.
If the values you supplied are correct, then you will need to swap a couple of nibbles (a nibble is half a byte) relative to this. Assuming you only want to swap the 1 in the second byte (outbuf[1]) and the zero in the third byte (outbuf[2]) then ...
Code:
// note: untested code follows; it shows the idea. Use at own risk
void your_possibly_wrong_convert_routine(unsigned long tdelay, unsigned char outbuf[])
{
unsigned char temp[2];
my_possibly_wrong_convert_routine(tdelay, outbuf);
temp[0] = (outbuf[1] % 0x10)*0x10 + outbuf[2] / 0x10;
temp[1] = (outbuf[2] % 0x10)*0x10 + outbuf[1] / 0x10;
outbuf[2] = temp[1];
outbuf[1] = temp[0];
}
The magic value here, 0x10 is 0xF + 1 (i.e. 16). Assuming an unsigned char has a range 0-255, dividing by 16 extracts the upper nibble, and modulo 16 extracts the lower nibble of a char. Then you just need to rebuild two characters with the nibbles swapped as needed.
This is not the only way to produce the bytes you suggest from a value 6844. If I've got the order wrong (check what other values should produce) then you will need to adjust.
Note that I've deliberately used unsigned types here, and assumed sizeof(unsigned long) is 4.