Programming/JavaScript & TypeScript

hex string <-> decimal

Bonita SY 2020. 12. 22. 20:27
728x90
반응형

 

[ utf-8 string | number ] -> hex string

  toHex(value: string | number) {
    let hexStr = '';

    if (typeof value === 'string') {
      for (let i = value.length - 1; i >= 0; i--) {
        hexStr =
          '%' +
          value
            .charCodeAt(i)
            .toString(16)
            .toUpperCase() +
          hexStr;
      }
    } else {
      let hex = value.toString(16).toUpperCase();
      if (hex.length !== 2) {
        hexStr = `%0${hex}`;
      } else {
        hexStr = `%${hex}`;
      }
    }

    return hexStr;
  }
728x90
반응형