Well, the example is using the MIFARE_Write
and MIFARE_Read
functions. These functions, as explained in the library, accept at least 16 bytes, so the 16-bytes buffer is the smallest you can read/write. Consequently I suggest you, if you don't have any additional data, to use 16-bytes IDs (you get a much wider code space).
If you strictly want to use 2 or 4-bytes integers, the first solution which comes to my mind is jose's one, so manually split the int in two (or the long in four) bytes and store them in the array. For instance
// Big endian format
dataBlock[idx] = (byte)(intValue >> 8); // Byte 1
dataBlock[idx+1] = (byte)(intValue); // Byte 0
// or
dataBlock[idx] = (byte)(longValue >> 24); // Byte 3
dataBlock[idx+1] = (byte)(longValue >> 16); // Byte 2
dataBlock[idx+2] = (byte)(longValue >> 8); // Byte 1
dataBlock[idx+3] = (byte)(longValue); // Byte 0
// Little endian format
dataBlock[idx] = (byte)(intValue); // Byte 0
dataBlock[idx+1] = (byte)(intValue >> 8); // Byte 1
// or
dataBlock[idx] = (byte)(longValue); // Byte 0
dataBlock[idx+1] = (byte)(longValue >> 8); // Byte 1
dataBlock[idx+2] = (byte)(longValue >> 16); // Byte 2
dataBlock[idx+3] = (byte)(longValue >> 24); // Byte 3
NOTE: idx
can be any value; the easiest approach is to put the int at the beginning (so substitute idx
with 0)
This is the safest way to handle this, since the endianness is explicit. You can, however, trust the compiler and use its implicit handling of multi-byte variables in this way:
*((int*)(&datablock[idx])) = intValue;
// or
*((long*)(&datablock[idx])) = longValue;
You take the cell where you want to put the beginning of the data, get its pointer, cast it to the pointer type you need, then write inside that pointer the value you want. Please note, however, that cells idx and idx+1 in the case of an int, or idx to idx+3 for long, will be written. If your array ends, you will pollute the memory in unpredictible ways (just like if you write dataBlock[18] = something
when dataBlock has 16 cells).
Note you cannot control the endianness of the byte array, but if you always use the same device to read and write you should not worry. FYI, at present the compiler used by Arduino IDE is little endian.
Note also that, for idx = 0
, (&datablock[idx])
can be simplified in (datablock)
.
To read back the data, you have the following ways
// Big endian format
intValue = (((int)dataBlock[idx]) << 8) | dataBlock[idx+1];
// or
longValue = (((long)dataBlock[idx]) << 24) | (((long)dataBlock[idx+1]) << 16) | (((long)dataBlock[idx+2]) << 8) | dataBlock[idx+3];
// Little endian format
intValue = (((int)dataBlock[idx+1]) << 8) | dataBlock[idx];
// or
longValue = (((long)dataBlock[idx+3]) << 24) | (((long)dataBlock[idx+2]) << 16) | (((long)dataBlock[idx+1]) << 8) | dataBlock[idx];
Or, in the last case,
intValue = *((int*)(&datablock[idx]));
// or
longValue = *((long*)(&datablock[idx]));