[sdiy] Pointers in C

René Schmitz uzs159 at uni-bonn.de
Sat Dec 31 17:56:43 CET 2011


Am 31.12.2011 13:36, schrieb Colin f:
>
>>    But I have a question, if I have a pointer to an unsigned
>> long int (32bits) and I want to access it as four unsigned
>> chars, do I just read a char and increase the pointer? for example;
>>
>> int *my_ptr = my_unsigned_long_int;
>> unsigned char FirstByte = *my_ptr;
>> my_ptr++;
>> unsigned char SecondByte = *my_ptr;
>> my_ptr++;
>> unsigned char ThirdByte = *my_ptr;
>> my_ptr++;
>> unsigned char FourthByte = *my_ptr;
>
> When you do my_ptr++ it will increment by 4, since the pointer is defined as
> pointing to an int.
>
> This...
>
> char *my_ptr;
> my_ptr = (char *)my_unsigned_long_int;
>
> unsigned char FirstByte = *my_ptr;
> my_ptr++;
> unsigned char SecondByte = *my_ptr;
> my_ptr++;
> unsigned char ThirdByte = *my_ptr;
> my_ptr++;
> unsigned char FourthByte = *my_ptr;
>
> ...is more what you want, I think.
>
> Cheers,
> Colin f


I'd just dereference the 32bit pointer, and get the individual bytes by 
bit masking and shifting instead.
i.e.

unsigned long allbytes = *my_unsigned_long_ptr;
unsigned char LSByte = allbytes && 0x0ff;
unsigned char secondbyte = (allbytes && 0x0ff00)>>8;
unsigned char thirdbyte = (allbytes && 0x0ff0000L)>>16;
unsigned char MSByte = (allbytes && 0x0ff000000L)>>24;

In my opinion this gives much less confusion with endianess...

Cheers,
  René

-- 
uzs159 at uni-bonn.de
http://www.uni-bonn.de/~uzs159



More information about the Synth-diy mailing list