81 lines
1.7 KiB
JavaScript
81 lines
1.7 KiB
JavaScript
/*
|
|
* Copyright (C) Sapphirecode - All Rights Reserved
|
|
* This file is part of Encoding-Helper which is released under MIT.
|
|
* See file 'LICENSE' for full license details.
|
|
* Created by Timo Hocker <timo@sapphirecode.ovh>, March 2020
|
|
*/
|
|
|
|
|
|
// @ts-nocheck
|
|
/* eslint-disable no-magic-numbers */
|
|
'use strict';
|
|
|
|
/**
|
|
* encode a string to base64
|
|
*
|
|
* @param {string} str string to encode
|
|
* @param {string} encoding encoding the string is in
|
|
* @returns {string} base64
|
|
*/
|
|
function to_b64 (str, encoding = '') {
|
|
const buf = Buffer.from (str, encoding);
|
|
return buf.toString ('base64');
|
|
}
|
|
|
|
/**
|
|
* encode a string to utf-8
|
|
*
|
|
* @param {string} str string to encode
|
|
* @param {string} encoding encoding the string is in
|
|
* @returns {string} utf-8
|
|
*/
|
|
function to_utf8 (str, encoding) {
|
|
const buf = Buffer.from (str, encoding);
|
|
return buf.toString ('utf-8');
|
|
}
|
|
|
|
/**
|
|
* encode a string to hex
|
|
*
|
|
* @param {string} str string to encode
|
|
* @param {string} encoding encoding the string is in
|
|
* @returns {string} hex
|
|
*/
|
|
function to_hex (str, encoding = '') {
|
|
const buf = Buffer.from (str, encoding);
|
|
return buf.toString ('hex');
|
|
}
|
|
|
|
/**
|
|
* encode a number to hex
|
|
*
|
|
* @param {number} n number to encode
|
|
* @param {number} padding minumum length of output
|
|
* @returns {string} hex
|
|
*/
|
|
function num_to_hex (n, padding = 0) {
|
|
const res = n.toString (16);
|
|
if (res.length < padding)
|
|
return '0'.repeat (padding - res.length) + res;
|
|
return res;
|
|
}
|
|
|
|
/**
|
|
* decode a number from hex
|
|
*
|
|
* @param {string} h hex to decode
|
|
* @returns {number} number
|
|
*/
|
|
function hex_to_num (h) {
|
|
return parseInt (h, 16);
|
|
}
|
|
|
|
module.exports = {
|
|
to_b64,
|
|
to_hex,
|
|
to_utf8,
|
|
num_to_hex,
|
|
hex_to_num
|
|
};
|
|
|