Forgive me if this comes across as a trivial question - I'm usually a control systems guy (plc's and automation) but have found myself involved in some embedded micro-controller and PC projects lately.
Let's say I have a function that accepts a pointer to an array of 'command bytes', typically 5 or 10 bytes in length, like so:
char cmd_i2c_read(unsigned char *cmd, unsigned short cmd_len) { ... }
I want to decode the command bytes (*cmd).
Is it better form to:
Create local variables indicating the purpose of each byte:
unsigned char device_address = cmd[2];
unsigned char register_address = cmd[3];
unsigned char num_bytes = cmd[4];
// use the local variables:
if(num_bytes &le 0xFF) {
do_stuff(device_address, register_address, num_bytes);
}
Create local pointers:
unsigned char *device_address = &cmd[2];
unsigned char *register_address = &cmd[3];
unsigned char *num_bytes = &cmd[4];
// use the pointers:
if(*num_bytes &le 0xFF) {
do_stuff(*device_address, *register_address, *num_bytes);
}
Index the *cmd array directly:if(cmd[4] <= 0xFF) {
do_stuff(cmd[2], cmd[3], cmd[4]);
}
Option 1 is clear but a bit wordy. I don't like 2 at all, and 3 is hard to understand. Personally I prefer to use structs for this sort of thing.
typedef struct {
unsigned char whatever[2];
unsigned char device_address;
unsigned char register_address;
unsigned char num_bytes;
} CMD;
CMD * pcmd = (CMD *)&cmd[0];
// use the local variables:
if(num_bytes ≤ 0xFF) {
do_stuff(pcmd->device_address, pcmd->register_address, pcmd->num_bytes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With