-2

That code will run on a payment device (POS). I have to use legacy C (not C# or C++) for that purpose.

I am trying to prepare a simple Mifare card read/write software data. Below document is my reference and I am trying to achieve what is on page 9, 8.6.2.1 Value blocks explains. http://www.nxp.com/documents/data_sheet/MF1S50YYX_V1.pdf

I just know very basics of C. All my searches in The Internet have failed. According to document:

1- There is integer variable with value of 1234567.

2- There is char array[4] which should have hex of above value which is 0x0012D687

3- I am supposed to invert that char array[4] and reach value of 0xFFED2978

I need to do some other things but I have stuck in number 3 above. What I have tried lastly is

int value = 1234567;
char valuebuffer[4];
char invertbuffer[4];

sprintf(valuebuffer, "%04x", value);  
for(i = 0;  i < sizeof(valuebuffer);  i++ )
{   
    invertbuffer[i] ^= valuebuffer[i];  
}

When I print, I read some other value in invertbuffer and not 0xFFED2978

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106

2 Answers2

0

Seems like you're making it more complicated than it needs to be. You can do the binary inversion on the int variable rather than messing around with individual bytes.

int value = 1234567;
int inverted= ~ value;

printf("%x\n",value);
printf("%x\n",inverted);

gives you output of

12d687

ffed2978

Community
  • 1
  • 1
Chris Turner
  • 8,082
  • 1
  • 14
  • 18
0

First of all, you must use the types from stdint.h and not char, because the latter has implementation-defined signedness and is therefore overall unsuitable for holding raw binary data.

With that sorted, you can use a union for maximum flexibility:

#include <stdint.h>
#include <stdio.h>

typedef union
{
  uint32_t u32;
  uint8_t  u8 [4];
} uint32_union_t;

int main (void)
{
  uint32_union_t x;
  x.u32 = 1234567;

  for(size_t i=0; i<4; i++)
  {
    printf("%X ", x.u8[i]);
  }
  printf("\n");

  x.u32 = ~x.u32;

  for(size_t i=0; i<4; i++)
  {
    printf("%X ", x.u8[i]);
  }
  printf("\n");
}

Notably, the access order of the u8 is endianess dependent. This might be handy when dealing with something like RFID, which doesn't necessarily have the same network endianess as your MCU.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Not _must_ but _should_ use the types from ``. `unsigned char` is perfectly usable as a non-negative integer of at least 8 bits, and similarly `unsigned long` is a non-negative integer of at least 32 bits everywhere. – mlp Dec 12 '18 at 19:42