encoding-helper/index.js

75 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-03-04 12:15:08 +01:00
/*
* Copyright (C) Sapphirecode - All Rights Reserved
2020-03-25 17:03:40 +01:00
* This file is part of Encoding-Helper which is released under MIT.
* See file 'LICENSE' for full license details.
2020-03-04 12:15:08 +01:00
* Created by Timo Hocker <timo@scode.ovh>, March 2020
*/
// @ts-nocheck
'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
* @returns {string} hex
*/
function num_to_hex (n) {
return n.toString(16);
}
/**
* decode a number from hex
*
* @param {string} h hex to decode
* @returns {number} number
*/
function hex_to_num (h) {
return parseInt(h, 16);
}
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
};