Napisałem sobie 3 metody które robią to samo ale inaczej. Który sposób jest lepszy a może macie inne pomysły?
https://onlinegdb.com/rk4AtzlX8
Dla tych co nie lubią powyższej stronki:
Code: Select all
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
const char* stringAddress = "282DF42105000094";
uint8_t* getDeviceAddress1()
{
static uint8_t addrv[8] = { 0 };
sscanf(stringAddress, "%2hhx %2hhx %2hhx %2hhx %2hhx %2hhx %2hhx %2hhx",
&addrv[0], &addrv[1], &addrv[2], &addrv[3],
&addrv[4], &addrv[5], &addrv[6], &addrv[7]);
return addrv;
}
void getDeviceAddress2(uint8_t *buf)
{
uint8_t addrv[8] = { 0 };
sscanf(stringAddress, "%2hhx %2hhx %2hhx %2hhx %2hhx %2hhx %2hhx %2hhx",
&addrv[0], &addrv[1], &addrv[2], &addrv[3],
&addrv[4], &addrv[5], &addrv[6], &addrv[7]);
for (int i = 0; i < 8; i++) {
buf[i] = (__typeof__(buf[0])) addrv[i];
}
}
void getDeviceAddress3(uint8_t *buf)
{
uint8_t lengthDestination = 8;
uint8_t addrv[lengthDestination] = { 0 };
sscanf(stringAddress, "%2hhx %2hhx %2hhx %2hhx %2hhx %2hhx %2hhx %2hhx",
&addrv[0], &addrv[1], &addrv[2], &addrv[3],
&addrv[4], &addrv[5], &addrv[6], &addrv[7]);
memcpy(buf, addrv, lengthDestination);
//memcpy(buf, addrv, lengthDestination - 1);
//buf[lengthDestination - 1] = 0;
}
void print(uint8_t * buf) {
char strAddr[64];
sprintf(
strAddr,
"{0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X}",
buf[0],
buf[1],
buf[2],
buf[3],
buf[4],
buf[5],
buf[6],
buf[7]);
printf( "address %s\n", strAddr);
}
int main() {
uint8_t *buf1 = getDeviceAddress1();
uint8_t buf2[8];
getDeviceAddress2(buf2);
uint8_t buf3[8];
getDeviceAddress3(buf3);
print(buf1);
print(buf2);
print(buf3);
}
