encoding-helper/index.js

81 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-03-04 12:15:08 +01:00
/*
* Copyright (C) Sapphirecode - All Rights Reserved
2020-05-15 16:08:01 +02:00
* This file is part of encoding-helper which is released under MIT.
2020-03-25 17:03:40 +01:00
* See file 'LICENSE' for full license details.
2020-05-15 16:08:01 +02:00
* Created by Timo Hocker <timo@scode.ovh>, May 2020
2020-03-04 12:15:08 +01:00
*/
2020-04-24 16:13:54 +02:00
2020-03-04 12:15:08 +01:00
// @ts-nocheck
2020-04-24 16:13:54 +02:00
/* eslint-disable no-magic-numbers */
2020-03-04 12:15:08 +01:00
'use strict';
/**
* encode a string to base64
*
* @param {string} str string to encode
* @param {string} encoding encoding the string is in
* @returns {string} base64
*/
2020-03-26 07:58:10 +01:00
function to_b64 (str, encoding = '') {
2020-03-04 12:15:08 +01:00
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
*/
2020-03-26 07:58:10 +01:00
function to_hex (str, encoding = '') {
2020-03-04 12:15:08 +01:00
const buf = Buffer.from (str, encoding);
return buf.toString ('hex');
}
2020-04-24 16:11:32 +02:00
/**
* encode a number to hex
*
* @param {number} n number to encode
2020-04-24 16:57:50 +02:00
* @param {number} padding minumum length of output
2020-04-24 16:11:32 +02:00
* @returns {string} hex
*/
2020-04-24 16:57:50 +02:00
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;
2020-04-24 16:11:32 +02:00
}
/**
* decode a number from hex
*
* @param {string} h hex to decode
* @returns {number} number
*/
function hex_to_num (h) {
2020-04-24 16:13:54 +02:00
return parseInt (h, 16);
2020-04-24 16:11:32 +02:00
}
2020-03-04 12:15:08 +01:00
module.exports = {
to_b64,
to_hex,
2020-04-24 16:11:32 +02:00
to_utf8,
num_to_hex,
hex_to_num
2020-03-04 12:15:08 +01:00
};