capawesome-team / capacitor-nfc

⚡️ Capacitor plugin for reading and writing NFC tags.
https://capawesome.io/plugins/nfc/
MIT License
72 stars 14 forks source link

feat: `convertBytesToHexString` #7

Closed adnathanail closed 1 year ago

adnathanail commented 1 year ago

Is your feature request related to a problem? Please describe: I'm coming from using this old NFC reading package

https://github.com/chariotsolutions/phonegap-nfc

And it had a util function called toHex which converted a byte to its equivalent character in hexadecimal

https://github.com/chariotsolutions/phonegap-nfc/blob/d325b860af64869e4b6d7996c37d61d2492310d5/www/phonegap-nfc.js#L591

I extended this to convert an array of bytes to a string of hex chars joined by ':' which is a common representation format for an NFC ID

Describe the solution you'd like: I've rewritten this function to have a consistent API with convertBytesToString

function convertBytesToHexString(options: { bytes: number[] }): {
  text: string;
} {
  const { bytes } = options;
  const hexCharArray = bytes.map((byte) => {
    if (byte < 0) {
      byte = 256 + byte;
    }
    let hexChar: string = byte.toString(16); // convert number to hexadecimal equivalent
    if (hexChar.length === 1) {
      hexChar = '0'.concat(hexChar);
    }
    return hexChar.toUpperCase();
  });
  return {
    text: hexCharArray.join(':'),
  };
}

If you think it could be generally useful to others, feel free to include it!

robingenz commented 1 year ago

Thank you for the issue! Yes, this helper function is currently missing and i will include it in the next release. I also already have similar code in my nfc demo app: https://github.com/capawesome-team/capacitor-nfc-demo/blob/main/src/app/shared/pipes/bytes-to-hex/bytes-to-hex.pipe.ts

robingenz commented 1 year ago

This will be part of v0.3.1.