Compare commits

..
Author SHA1 Message Date
sharevb 71faa2bb0c feat(new tool): Hex Converter
Convert hex buffer to (un)signed integer/float
Fix #1447
2025-03-10 21:28:26 +01:00
18 changed files with 3052 additions and 2821 deletions

No files matched your search

+1 -4
View File
@@ -286,9 +286,6 @@
"watchTriggerable": true,
"watchWithFilter": true,
"whenever": true,
"toValue": true,
"injectLocal": true,
"provideLocal": true,
"useClipboardItems": true
"toValue": true
}
}
-9
View File
@@ -36,7 +36,6 @@ declare global {
const h: typeof import('vue')['h']
const ignorableWatch: typeof import('@vueuse/core')['ignorableWatch']
const inject: typeof import('vue')['inject']
const injectLocal: typeof import('@vueuse/core')['injectLocal']
const isDefined: typeof import('@vueuse/core')['isDefined']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
@@ -66,7 +65,6 @@ declare global {
const onUpdated: typeof import('vue')['onUpdated']
const pausableWatch: typeof import('@vueuse/core')['pausableWatch']
const provide: typeof import('vue')['provide']
const provideLocal: typeof import('@vueuse/core')['provideLocal']
const reactify: typeof import('@vueuse/core')['reactify']
const reactifyObject: typeof import('@vueuse/core')['reactifyObject']
const reactive: typeof import('vue')['reactive']
@@ -130,7 +128,6 @@ declare global {
const useBrowserLocation: typeof import('@vueuse/core')['useBrowserLocation']
const useCached: typeof import('@vueuse/core')['useCached']
const useClipboard: typeof import('@vueuse/core')['useClipboard']
const useClipboardItems: typeof import('@vueuse/core')['useClipboardItems']
const useCloned: typeof import('@vueuse/core')['useCloned']
const useColorMode: typeof import('@vueuse/core')['useColorMode']
const useConfirmDialog: typeof import('@vueuse/core')['useConfirmDialog']
@@ -329,7 +326,6 @@ declare module 'vue' {
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly ignorableWatch: UnwrapRef<typeof import('@vueuse/core')['ignorableWatch']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly injectLocal: UnwrapRef<typeof import('@vueuse/core')['injectLocal']>
readonly isDefined: UnwrapRef<typeof import('@vueuse/core')['isDefined']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
@@ -359,7 +355,6 @@ declare module 'vue' {
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly provideLocal: UnwrapRef<typeof import('@vueuse/core')['provideLocal']>
readonly reactify: UnwrapRef<typeof import('@vueuse/core')['reactify']>
readonly reactifyObject: UnwrapRef<typeof import('@vueuse/core')['reactifyObject']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
@@ -423,7 +418,6 @@ declare module 'vue' {
readonly useBrowserLocation: UnwrapRef<typeof import('@vueuse/core')['useBrowserLocation']>
readonly useCached: UnwrapRef<typeof import('@vueuse/core')['useCached']>
readonly useClipboard: UnwrapRef<typeof import('@vueuse/core')['useClipboard']>
readonly useClipboardItems: UnwrapRef<typeof import('@vueuse/core')['useClipboardItems']>
readonly useCloned: UnwrapRef<typeof import('@vueuse/core')['useCloned']>
readonly useColorMode: UnwrapRef<typeof import('@vueuse/core')['useColorMode']>
readonly useConfirmDialog: UnwrapRef<typeof import('@vueuse/core')['useConfirmDialog']>
@@ -616,7 +610,6 @@ declare module '@vue/runtime-core' {
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly ignorableWatch: UnwrapRef<typeof import('@vueuse/core')['ignorableWatch']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly injectLocal: UnwrapRef<typeof import('@vueuse/core')['injectLocal']>
readonly isDefined: UnwrapRef<typeof import('@vueuse/core')['isDefined']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
@@ -646,7 +639,6 @@ declare module '@vue/runtime-core' {
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly provideLocal: UnwrapRef<typeof import('@vueuse/core')['provideLocal']>
readonly reactify: UnwrapRef<typeof import('@vueuse/core')['reactify']>
readonly reactifyObject: UnwrapRef<typeof import('@vueuse/core')['reactifyObject']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
@@ -710,7 +702,6 @@ declare module '@vue/runtime-core' {
readonly useBrowserLocation: UnwrapRef<typeof import('@vueuse/core')['useBrowserLocation']>
readonly useCached: UnwrapRef<typeof import('@vueuse/core')['useCached']>
readonly useClipboard: UnwrapRef<typeof import('@vueuse/core')['useClipboard']>
readonly useClipboardItems: UnwrapRef<typeof import('@vueuse/core')['useClipboardItems']>
readonly useCloned: UnwrapRef<typeof import('@vueuse/core')['useCloned']>
readonly useColorMode: UnwrapRef<typeof import('@vueuse/core')['useColorMode']>
readonly useConfirmDialog: UnwrapRef<typeof import('@vueuse/core')['useConfirmDialog']>
+8 -2
View File
@@ -83,6 +83,7 @@ declare module '@vue/runtime-core' {
GitMemo: typeof import('./src/tools/git-memo/git-memo.vue')['default']
'GitMemo.content': typeof import('./src/tools/git-memo/git-memo.content.md')['default']
HashText: typeof import('./src/tools/hash-text/hash-text.vue')['default']
HexConverter: typeof import('./src/tools/hex-converter/hex-converter.vue')['default']
HmacGenerator: typeof import('./src/tools/hmac-generator/hmac-generator.vue')['default']
'Home.page': typeof import('./src/pages/Home.page.vue')['default']
HtmlEntities: typeof import('./src/tools/html-entities/html-entities.vue')['default']
@@ -131,19 +132,24 @@ declare module '@vue/runtime-core' {
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDivider: typeof import('naive-ui')['NDivider']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NFormItem: typeof import('naive-ui')['NFormItem']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NP: typeof import('naive-ui')['NP']
NRadio: typeof import('naive-ui')['NRadio']
NRadioGroup: typeof import('naive-ui')['NRadioGroup']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NSpace: typeof import('naive-ui')['NSpace']
NTable: typeof import('naive-ui')['NTable']
NSwitch: typeof import('naive-ui')['NSwitch']
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
OtpCodeGeneratorAndValidator: typeof import('./src/tools/otp-code-generator-and-validator/otp-code-generator-and-validator.vue')['default']
PasswordStrengthAnalyser: typeof import('./src/tools/password-strength-analyser/password-strength-analyser.vue')['default']
+3
View File
@@ -53,6 +53,7 @@
"@vueuse/head": "^1.0.0",
"@vueuse/router": "^10.0.0",
"bcryptjs": "^2.4.3",
"byte-data": "^19.0.1",
"change-case": "^4.1.2",
"colord": "^2.9.3",
"composerize-ts": "^0.6.2",
@@ -67,6 +68,7 @@
"figlet": "^1.7.0",
"figue": "^1.2.0",
"fuse.js": "^6.6.2",
"hex-array": "^1.0.0",
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
@@ -115,6 +117,7 @@
"@types/bcryptjs": "^2.4.2",
"@types/crypto-js": "^4.1.1",
"@types/dompurify": "^3.0.5",
"@types/hex-array": "^1.0.2",
"@types/jsdom": "^21.0.0",
"@types/lodash": "^4.14.192",
"@types/mime-types": "^2.1.1",
+2211 -2458
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,250 @@
import { describe, expect, it } from 'vitest';
import { cleanHex, decodeNumber, decodeStruct, encodeStruct, getCoderFromTypeName, parseNumber } from './hex-converter.service';
describe('cleanHex', () => {
it('should remove 0x and \\x prefixes from a hex string', () => {
expect(cleanHex('0x1234')).toBe('1234');
expect(cleanHex('\\x1234')).toBe('1234');
expect(cleanHex('1234')).toBe('1234');
});
});
describe('decodeNumber', () => {
it('should convert a number to binary', () => {
expect(decodeNumber(10, 8, 'bin')).toBe('00001010');
});
it('should convert a number to hex', () => {
expect(decodeNumber(10, 8, 'hex')).toBe('0a');
});
it('should convert a number to character', () => {
expect(decodeNumber(65, 8, 'char')).toBe('A');
});
it('should return the number itself for decimal conversion', () => {
expect(decodeNumber(10, 8, 'dec')).toBe(10);
});
});
describe('parseNumber', () => {
it('should parse hexadecimal input correctly', () => {
expect(parseNumber('0x1F')).toBe(31);
});
it('should parse binary input correctly', () => {
expect(parseNumber('0b1101')).toBe(13);
});
it('should parse string input correctly into code points', () => {
expect(parseNumber('abc')).toEqual([97, 98, 99]);
});
it('should return number when input is already a number', () => {
expect(parseNumber(42)).toBe(42);
});
it('should return 0 for falsy input', () => {
expect(parseNumber('')).toBe(0);
});
});
describe('getCoderFromTypeName', () => {
it('should return correct coder options for a basic integer type', () => {
const result = getCoderFromTypeName('uint16');
expect(result.type.bits).toBe(16);
expect(result.type.signed).toBe(false);
expect(result.size).toBe(1);
});
it('should handle big-endian types correctly', () => {
const result = getCoderFromTypeName('int32be');
expect(result.type.bits).toBe(32);
expect(result.type.be).toBe(true);
});
it('should return correct coder options for a float type', () => {
const result = getCoderFromTypeName('float');
expect(result.type.bits).toBe(32);
expect(result.type.fp).toBe(true);
});
it('should return correct coder options for a character type', () => {
const result = getCoderFromTypeName('char[4]');
expect(result.type.bits).toBe(8);
expect(result.size).toBe(4);
expect(result.formatter(65, 8)).toBe('A');
});
});
describe('decodeStruct', () => {
it('should decode a flat struct correctly from a hex array', () => {
const struct = {
field1: 'uint16',
field2: 'char[3]',
};
const hexArray = new Uint8Array([0x01, 0x0, 0x61, 0x62, 0x63]);
const result = decodeStruct({ struct, hexArray });
expect(result.field1).toBe(1);
expect(result.field2).toBe('abc');
});
it('should decode a nested struct correctly', () => {
const struct = {
type: 'int8',
header: {
version: 'uint8',
type: 'uint16be',
},
payload: {
value: 'floatbe',
},
};
const hexArray = new Uint8Array([0xFF, 0x01, 0x00, 0x02, 0x3F, 0x80, 0x0, 0x0]); // float 1.0
const result = decodeStruct({ struct, hexArray });
expect(result).toEqual({
type: -1,
header: { version: 1, type: 2 },
payload: { value: 1.0 },
});
});
it('should throw on bad buffer length', () => {
const struct = {
type: 'int8',
header: {
version: 'uint8',
type: 'uint16be',
},
payload: {
value: 'floatbe',
},
};
const hexArray = new Uint8Array([0xFF, 0x01, 0x00, 0x02, 0x3F, 0x80]); // missing last two bytes
expect(() => decodeStruct({ struct, hexArray })).toThrowError(
'Bad buffer length reading value(floatbe) at offset 4',
);
});
it('should throw an error when decoding an unsupported array type', () => {
const struct = {
list: ['uint8'],
};
const hexArray = new Uint8Array([0x01, 0x02, 0x03]);
expect(() => decodeStruct({ struct, hexArray })).toThrowError(
'Cannot decode a struct with array',
);
});
it('should throw an error when decoding an unsized array type', () => {
const struct = {
list: 'uint8[]',
};
const hexArray = new Uint8Array([0x01, 0x02, 0x03]);
expect(() => decodeStruct({ struct, hexArray })).toThrowError(
'Unsupported unsized array: uint8[]',
);
});
});
describe('encodeStruct', () => {
it('should encode a flat struct correctly', () => {
const struct = {
field1: 'uint8',
field2: 'char[3]',
};
const jsonObject = {
field1: 1,
field2: 'abc',
};
const result = encodeStruct({ struct, jsonObject });
expect(result).toEqual(new Uint8Array([0x01, 0x61, 0x62, 0x63]));
});
it('should encode a nested struct correctly', () => {
const struct = {
type: 'int8',
header: {
version: 'uint8',
type: 'uint16be',
},
payload: {
value: 'floatbe',
},
};
const jsonObject = {
type: -1,
header: { version: 1, type: 2 },
payload: { value: 1.0 },
};
const result = encodeStruct({ struct, jsonObject });
expect(result).toEqual(new Uint8Array([0xFF, 0x01, 0x00, 0x02, 0x3F, 0x80, 0x0, 0x0]));
});
it('should throw an error if array size is incorrect', () => {
const struct = {
field1: 'uint8',
field2: 'char[3]',
};
const jsonObject = {
field1: 1,
field2: 'abcd', // Too long
};
expect(() => encodeStruct({ struct, jsonObject })).toThrowError(
'Unexpected array size \'field2\'=\'97,98,99,100\' expected 3 elements',
);
});
it('should throw an error if value type is incorrect', () => {
const struct = {
field1: 'uint8',
field2: 'char[3]',
};
const jsonObject = {
field1: 1,
field2: 123, // Invalid type
};
expect(() => encodeStruct({ struct, jsonObject })).toThrowError(
'Unexpected non array \'field2\'=\'123\'',
);
});
it('should throw an error if value type is incorrect', () => {
const struct = {
field1: 'uint8',
field2: 'int16',
};
const jsonObject = {
field1: 1,
field2: '123', // Invalid type
};
expect(() => encodeStruct({ struct, jsonObject })).toThrowError(
'Unexpected array size \'field2\'=\'49,50,51\' expected 1 elements',
);
});
it('should encode multiple integer types correctly', () => {
const struct = {
a: 'uint8',
b: 'uint16',
c: 'uint32',
};
const jsonObject = {
a: 1,
b: 513,
c: 67305985,
};
const result = encodeStruct({ struct, jsonObject });
expect(result).toEqual(new Uint8Array([0x01, 0x01, 0x02, 0x01, 0x02, 0x03, 0x04]));
});
});
@@ -0,0 +1,193 @@
import { pack, unpack } from 'byte-data';
export type Conversion = 'dec' | 'bin' | 'hex' | 'char';
export function cleanHex(hex: string): string {
return hex.replace(/\\x|0x/g, '');
}
export function decodeNumber(n: number, bits: number, conv: Conversion) {
if (conv === 'bin') {
return n.toString(2).padStart(bits, '0');
}
if (conv === 'hex') {
return n.toString(16).padStart(bits / 4, '0');
}
if (conv === 'char') {
return String.fromCodePoint(n);
}
return n;
}
export function parseNumber(input: string | number): number | number[] {
if (!input) {
return 0;
}
if (typeof input === 'number') {
return input;
}
if (/^0x[0-9a-fA-F]+$/.test(input)) {
return Number.parseInt(input.substring(2), 16); // Parse as hexadecimal
}
else if (/^0b[01]+$/.test(input)) {
return Number.parseInt(input.substring(2), 2); // Parse as binary
}
return [...input].map(c => c.codePointAt(0) || 0);
}
function mergeModelAndObject(model: Record<string, any>, object: Record<string, any>): Record<string, any> {
const merged: Record<string, any> = {};
for (const key in model) {
if (Object.prototype.hasOwnProperty.call(model, key)) {
if (Array.isArray(object[key])) {
merged[key] = [model[key], object[key].map(parseNumber)];
}
else if (typeof object[key] === 'object' && !Array.isArray(object[key])) {
merged[key] = mergeModelAndObject(model[key], object[key]);
}
else {
merged[key] = [model[key], parseNumber(object[key])];
}
}
}
return merged;
}
interface CoderOption {
type: {
bits: number
fp?: boolean
be?: boolean
signed?: boolean
}
size: number
formatter: (n: number, bits: number) => string | number
join?: boolean
};
export function getCoderFromTypeName(typeName: string): CoderOption {
if (typeName.includes('[]')) {
throw new Error(`Unsupported unsized array: ${typeName}`);
}
const [, prefix, baseTypeName, bigEndian, arraySize] = /^((?:0x|0b)?)(u?int\d+|w?char|half|float|double)(be)?(?:\[(\d+)\])?$/.exec(typeName) || [];
let conv = 'dec';
if (prefix === '0x') {
conv = 'hex';
}
if (prefix === '0b') {
conv = 'bin';
}
const arraySizeNumber = Number.isNaN(Number(arraySize)) ? 1 : Number(arraySize);
if (baseTypeName === 'char' || baseTypeName === 'wchar') {
return {
type: {
bits: baseTypeName === 'char' ? 8 : 16,
be: !!bigEndian,
},
size: arraySizeNumber,
formatter: n => String.fromCodePoint(n),
join: true,
};
}
if (baseTypeName === 'float' || baseTypeName === 'double' || baseTypeName === 'half') {
return {
type: {
bits: baseTypeName === 'float' ? 32 : (baseTypeName === 'double' ? 64 : 16),
be: !!bigEndian,
fp: true,
},
size: arraySizeNumber,
formatter: n => n,
};
}
const [, unsigned, bits] = /^(u?)int(\d+)$/.exec(baseTypeName || '') || [];
return {
type: {
bits: Number(bits),
be: !!bigEndian,
signed: !unsigned,
},
size: arraySizeNumber,
formatter: (n, bits) => decodeNumber(n, bits, conv as Conversion),
};
}
export function decodeStruct({ struct, hexArray }: { struct: object; hexArray: Uint8Array }) {
let offset = 0;
const readMember = (obj: any) => {
const result: Record<string, any> = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (Array.isArray(obj[key])) {
throw new TypeError(`Cannot decode a struct with array (key=${key}). Must be expressed as string with fixed length`);
}
else if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
result[key] = readMember(obj[key]);
}
else {
const coderOption = getCoderFromTypeName(obj[key]);
const arr = [];
for (let i = 0; i < coderOption.size; i++) {
const dataSize = Math.ceil(coderOption.type.bits / 8);
if (offset + dataSize > hexArray.length) {
throw new Error(`Bad buffer length reading ${key}(${obj[key]}) at offset ${offset}`);
}
arr.push(coderOption.formatter(unpack(hexArray, coderOption.type, offset), coderOption.type.bits));
offset += dataSize;
}
if (coderOption.join) {
result[key] = arr.join('');
}
else {
result[key] = coderOption.size > 1 ? arr : arr[0];
}
}
}
}
return result;
};
return readMember(struct);
}
export function encodeStruct({ struct, jsonObject }: { struct: object; jsonObject: object }): Uint8Array {
const mergedObject = mergeModelAndObject(struct, jsonObject);
let buffer: Array<number> = [];
const writeMember = (obj: any) => {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
writeMember(obj[key]);
}
else if (Array.isArray(obj[key])) {
const [typeName, value] = obj[key];
const coderOption = getCoderFromTypeName(typeName);
if (coderOption.size > 1 && !Array.isArray(value)) {
throw new TypeError(`Unexpected non array '${key}'='${value}'`);
}
if (Array.isArray(value) && value.length !== coderOption.size) {
throw new TypeError(`Unexpected array size '${key}'='${value}' expected ${coderOption.size} elements`);
}
const valueArr = !Array.isArray(value) ? [value] : value;
for (let i = 0; i < coderOption.size; i++) {
buffer = [...buffer, ...pack(valueArr[i], coderOption.type)];
}
}
else {
throw new TypeError(`Unexpected '${key}'='${obj[key]}'`);
}
}
}
};
writeMember(mergedObject);
return new Uint8Array(buffer);
}
+303
View File
@@ -0,0 +1,303 @@
<script setup lang="ts">
import hexArray from 'hex-array';
import { packArray, packString, unpackArray, unpackString } from 'byte-data';
import JSON5 from 'json5';
import { type Conversion, cleanHex, decodeNumber, decodeStruct, encodeStruct } from './hex-converter.service';
import { useValidation } from '@/composable/validation';
const mode = ref<'simple' | 'struct'>('simple');
const bits = ref(32);
const floatingPoint = ref(false);
const signed = ref(false);
const bigEndian = ref(false);
const decodeAs = ref<'dec' | 'bin' | 'hexa' | 'char' | 'utf8'>('dec');
const uppercase = ref(false);
const grouping = ref(1);
const rowlength = ref(0);
const hexInput = ref('');
const decodedOutput = computed(() => {
try {
const buffer = hexArray.fromString(cleanHex(hexInput.value));
if (decodeAs.value === 'utf8') {
return unpackString(buffer);
}
else {
return unpackArray(buffer, {
bits: bits.value,
fp: floatingPoint.value,
signed: signed.value,
be: bigEndian.value,
}, 0, buffer.length, true).map(n => decodeNumber(n, bits.value, decodeAs.value as Conversion)).join(' ');
}
}
catch (e: any) {
return e.toString();
}
});
const numberInput = ref('');
const encodedOutput = computed(() => {
try {
const values = numberInput.value.split(/\s+/).map(Number);
return hexArray.toString(
new Uint8Array(
packArray(values, {
bits: bits.value,
fp: floatingPoint.value,
signed: signed.value,
be: bigEndian.value,
})),
{
uppercase: uppercase.value,
grouping: grouping.value,
rowlength: rowlength.value,
},
);
}
catch (e: any) {
return e.toString();
}
});
const stringInput = ref('');
const utf8Output = computed(() => {
try {
return hexArray.toString(
new Uint8Array(packString(stringInput.value)),
{
uppercase: uppercase.value,
grouping: grouping.value,
rowlength: rowlength.value,
},
);
}
catch (e: any) {
return e.toString();
}
});
const structDefinition = ref(`{
x: "int32",
y: "int32",
}`);
const structDefinitionValidation = useValidation({
source: structDefinition,
rules: [
{
message: 'Struct definition is not a valid JSON',
validator: value => JSON5.parse(value.trim()),
},
],
});
const hexStructInput = ref('');
const decodedStructOutput = computed(() => {
try {
return JSON.stringify(
decodeStruct({
struct: JSON5.parse(structDefinition.value),
hexArray: hexArray.fromString(cleanHex(hexStructInput.value)),
}),
null, 2);
}
catch (e: any) {
return e.toString();
}
});
const jsonStructInput = ref('');
const encodedStructOutput = computed(() => {
try {
return hexArray.toString(
encodeStruct({
struct: JSON5.parse(structDefinition.value),
jsonObject: JSON5.parse(jsonStructInput.value),
}), {
uppercase: uppercase.value,
grouping: grouping.value,
rowlength: rowlength.value,
});
}
catch (e: any) {
return e.toString();
}
});
</script>
<template>
<div>
<n-radio-group v-model:value="mode" name="radiogroup" mb-2 flex justify-center>
<n-space>
<n-radio
value="simple"
label="Simple Encoder/Decoder"
/>
<n-radio
value="struct"
label="C/C++ typed struct"
/>
</n-space>
</n-radio-group>
<div v-if="mode === 'simple'">
<c-card title="Hex Options" mb-1>
<c-select
v-model:value="decodeAs"
label="Decode/Encode As:"
label-position="left" mb-1
:options="[{ value: 'dec', label: 'Decimal' }, { value: 'bin', label: 'Binary' }, { value: 'hex', label: 'Hexadecimal' }, { value: 'char', label: 'Char/ASCII' }, { value: 'utf8', label: 'UTF8 string' }]"
/>
<n-space v-if="decodeAs !== 'utf8'" align="baseline" justify="center">
<n-form-item label="Bits:" label-placement="left">
<n-input-number v-model:value="bits" :min="1" style="width: 6em" />
</n-form-item>
<n-form-item>
<n-checkbox v-model:checked="floatingPoint">
Floating Point
</n-checkbox>
</n-form-item>
<n-form-item>
<n-checkbox v-model:checked="signed">
Signed
</n-checkbox>
</n-form-item>
<n-form-item>
<n-checkbox v-model:checked="bigEndian">
Big Endian
</n-checkbox>
</n-form-item>
</n-space>
</c-card>
<c-card title="Hex Data Decoder" mb-3>
<c-input-text
v-model:value="hexInput"
multiline
placeholder="Put your Hex data here..."
rows="2"
label="Hex Data to decode"
raw-text
mb-5
/>
<n-form-item label="Your decoded values:">
<textarea-copyable :value="decodedOutput" />
</n-form-item>
</c-card>
<c-card v-if="decodeAs !== 'utf8'" title="Hex Data Encoder" mt-3>
<c-input-text
v-model:value="numberInput"
multiline
placeholder="Put your Numbers array here..."
rows="2"
label="Numbers array to encode"
raw-text
mb-5
/>
<n-form-item label="Your encoded numbers array as Hex:">
<textarea-copyable :value="encodedOutput" />
</n-form-item>
</c-card>
<c-card v-if="decodeAs === 'utf8'" title="Hex UTF8 String Encoder" mt-3>
<c-input-text
v-model:value="stringInput"
multiline
placeholder="Put your text here..."
rows="5"
label="String to encode"
raw-text
mb-5
/>
<n-form-item label="Your encoded string as UTF8 Hex:">
<textarea-copyable :value="utf8Output" />
</n-form-item>
</c-card>
<c-card title="Hex Encoding Output" mt-1>
<n-space align="baseline" justify="center">
<n-form-item label="Uppercase" label-placement="left">
<n-switch v-model:value="uppercase" />
</n-form-item>
<n-form-item label="Group by" label-placement="left">
<n-input-number v-model:value="grouping" :min="0" style="width: 6em" mr-1 /> digits (0 = no grouping)
</n-form-item>
<n-form-item label="Split as rows by" label-placement="left">
<n-input-number v-model:value="rowlength" :min="0" style="width: 6em" mr-1 /> group of digits (0 = no rows)
</n-form-item>
</n-space>
</c-card>
</div>
<div v-if="mode === 'struct'">
<c-card title="Struct Definition">
<c-input-text
v-model:value="structDefinition"
multiline
placeholder="Put your Struct defintion here..."
rows="5"
label="C/C+ like struct definition"
raw-text
mb-5
:validation="structDefinitionValidation"
/>
<details>
<summary>Instructions</summary>
<n-p>
Define you struct definition in JSON format: keys = struct member names ; value = type
<br>
Types syntax: u?int{size}(be)? | float(be)? | double(be)? | char | wchar(be)? | &lt;type&gt;[{array size}]
<br>
where "u" means "unsigned" ; "be" means "Big Endian" ; {size} is number of bits ; {array size} fixed size for arrays
<br>
can prefix integer with 0x or 0b to display as hex and binary
</n-p>
</details>
</c-card>
<c-card title="Hex Struct Decoder" m-t-1>
<c-input-text
v-model:value="hexStructInput"
multiline
placeholder="Put your Hex data here..."
rows="5"
label="Hex Data to decode"
raw-text
mb-5
/>
<n-form-item label="Your decoded values:">
<textarea-copyable :value="decodedStructOutput" />
</n-form-item>
</c-card>
<c-card title="Hex Struct Encoder" m-t-1>
<c-input-text
v-model:value="jsonStructInput"
multiline
placeholder="Put your Struct to encode here..."
rows="5"
label="Struct json to encode"
raw-text
mb-5
/>
<n-form-item label="Your encoded struct as Hex:">
<textarea-copyable :value="encodedStructOutput" />
</n-form-item>
</c-card>
<c-card title="Hex Encoding Output" mt-1>
<n-space align="baseline" justify="center">
<n-form-item label="Uppercase" label-placement="left">
<n-switch v-model:value="uppercase" />
</n-form-item>
<n-form-item label="Group by" label-placement="left">
<n-input-number v-model:value="grouping" :min="0" style="width: 6em" mr-1 /> digits (0 = no grouping)
</n-form-item>
<n-form-item label="Split as rows by" label-placement="left">
<n-input-number v-model:value="rowlength" :min="0" style="width: 6em" mr-1 /> group of digits (0 = no rows)
</n-form-item>
</n-space>
</c-card>
</div>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
import { Binary } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Hex Encoder/Decoder',
path: '/hex-converter',
description: 'Encode and decode Hex buffers to number (bits, endianess, sign or floating point or chars) and structures',
keywords: ['hex', 'encode', 'decode', 'endianess', 'float', 'bits', 'hex', 'struct'],
component: () => import('./hex-converter.vue'),
icon: Binary,
createdAt: new Date('2025-02-09'),
});
+2
View File
@@ -2,6 +2,7 @@ import { tool as base64FileConverter } from './base64-file-converter';
import { tool as base64StringConverter } from './base64-string-converter';
import { tool as basicAuthGenerator } from './basic-auth-generator';
import { tool as emailNormalizer } from './email-normalizer';
import { tool as hexConverter } from './hex-converter';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
@@ -98,6 +99,7 @@ export const toolsByCategory: ToolCategory[] = [
components: [
dateTimeConverter,
baseConverter,
hexConverter,
romanNumeralConverter,
base64StringConverter,
base64FileConverter,
@@ -1,12 +1,12 @@
import { expect, test } from '@playwright/test';
test.describe('Tool - Text to UTF-8 binary', () => {
test.describe('Tool - Text to ASCII binary', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/text-to-binary');
});
test('Has correct title', async ({ page }) => {
await expect(page).toHaveTitle('Text to UTF-8 binary - IT Tools');
await expect(page).toHaveTitle('Text to ASCII binary - IT Tools');
});
test('Text to binary conversion', async ({ page }) => {
@@ -17,9 +17,7 @@ test.describe('Tool - Text to UTF-8 binary', () => {
});
test('Binary to text conversion', async ({ page }) => {
await page
.getByTestId('binary-to-text-input')
.fill('01101001 01110100 00101101 01110100 01101111 01101111 01101100 01110011');
await page.getByTestId('binary-to-text-input').fill('01101001 01110100 00101101 01110100 01101111 01101111 01101100 01110011');
const text = await page.getByTestId('binary-to-text-output').inputValue();
expect(text).toEqual('it-tools');
@@ -1,103 +1,32 @@
import { describe, expect, it } from 'vitest';
import { convertTextToUtf8Binary, convertUtf8BinaryToText } from './text-to-binary.models';
import { convertAsciiBinaryToText, convertTextToAsciiBinary } from './text-to-binary.models';
describe('text-to-binary', () => {
const utf8Tests = [
{
text: '文字',
binary: '11100110 10010110 10000111 11100101 10101101 10010111',
decimal: '',
octal: '',
hex: '',
},
{
text: '💩',
binary: '11110000 10011111 10010010 10101001',
decimal: '',
octal: '',
hex: '',
},
];
describe('convertTextToUtf8Binary', () => {
it('a text string is converted to its UTF-8 binary representation', () => {
expect(convertTextToUtf8Binary('A')).toBe('01000001');
expect(convertTextToUtf8Binary('A', { base: 8 })).toBe('0101');
expect(convertTextToUtf8Binary('A', { base: 10 })).toBe('65');
expect(convertTextToUtf8Binary('A', { base: 16 })).toBe('41');
expect(convertTextToUtf8Binary('hello')).toBe('01101000 01100101 01101100 01101100 01101111');
expect(convertTextToUtf8Binary('hello', { base: 8 })).toBe('0150 0145 0154 0154 0157');
expect(convertTextToUtf8Binary('hello', { base: 10 })).toBe('104 101 108 108 111');
expect(convertTextToUtf8Binary('hello', { base: 16 })).toBe('68 65 6c 6c 6f');
expect(convertTextToUtf8Binary('')).toBe('');
describe('convertTextToAsciiBinary', () => {
it('a text string is converted to its ascii binary representation', () => {
expect(convertTextToAsciiBinary('A')).toBe('01000001');
expect(convertTextToAsciiBinary('hello')).toBe('01101000 01100101 01101100 01101100 01101111');
expect(convertTextToAsciiBinary('')).toBe('');
});
it('the separator between octets can be changed', () => {
expect(convertTextToUtf8Binary('hello', { separator: '' })).toBe('0110100001100101011011000110110001101111');
expect(convertTextToUtf8Binary('hello', { separator: '-' })).toBe('01101000-01100101-01101100-01101100-01101111');
expect(convertTextToUtf8Binary('hello', { separator: '-', base: 16 })).toBe('68-65-6c-6c-6f');
});
it('works with non-ASCII input', () => {
for (const { text, binary } of utf8Tests) {
const converted = convertTextToUtf8Binary(text);
expect(converted).toBe(binary);
}
expect(convertTextToUtf8Binary('💩 A', { base: 2 })).toBe('11110000 10011111 10010010 10101001 00100000 01000001');
expect(convertTextToUtf8Binary('💩 A', { base: 8 })).toBe('0360 0237 0222 0251 040 0101');
expect(convertTextToUtf8Binary('💩 A', { base: 10 })).toBe('240 159 146 169 32 65');
expect(convertTextToUtf8Binary('💩 A', { base: 16 })).toBe('f0 9f 92 a9 20 41');
expect(convertTextToAsciiBinary('hello', { separator: '' })).toBe('0110100001100101011011000110110001101111');
});
});
describe('convertUtf8BinaryToText', () => {
describe('convertAsciiBinaryToText', () => {
it('an ascii binary string is converted to its text representation', () => {
expect(convertUtf8BinaryToText('01101000 01100101 01101100 01101100 01101111')).toBe('hello');
expect(convertUtf8BinaryToText('01101000 01100101 01101100 01101100 01101111', { base: 2 })).toBe('hello');
expect(convertUtf8BinaryToText('0150 0145 0154 0154 0157', { base: 8 })).toBe('hello');
expect(convertUtf8BinaryToText('104 101 108 108 111', { base: 10 })).toBe('hello');
expect(convertUtf8BinaryToText('68 65 6c 6c 6f', { base: 16 })).toBe('hello');
expect(convertUtf8BinaryToText('11110000 10011111 10010010 10101001 00100000 01000001', { base: 2 })).toBe('💩 A');
expect(convertUtf8BinaryToText('0360 0237 0222 0251 040 0101', { base: 8 })).toBe('💩 A');
expect(convertUtf8BinaryToText('240 159 146 169 32 65', { base: 10 })).toBe('💩 A');
expect(convertUtf8BinaryToText('f0 9f 92 a9 20 41', { base: 16 })).toBe('💩 A');
expect(convertUtf8BinaryToText('')).toBe('');
expect(convertUtf8BinaryToText('01000001')).toBe('A');
expect(convertUtf8BinaryToText('0101', { base: 8 })).toBe('A');
expect(convertUtf8BinaryToText('65', { base: 10 })).toBe('A');
expect(convertUtf8BinaryToText('41', { base: 16 })).toBe('A');
expect(convertAsciiBinaryToText('01101000 01100101 01101100 01101100 01101111')).toBe('hello');
expect(convertAsciiBinaryToText('01000001')).toBe('A');
expect(convertTextToAsciiBinary('')).toBe('');
});
it('the given string is cleaned before conversion', () => {
expect(convertUtf8BinaryToText(' 01000 001garbage')).toBe('A');
expect(convertUtf8BinaryToText(' 65garbage', { base: 10 })).toBe('A');
expect(convertUtf8BinaryToText(' 41xxxx', { base: 16 })).toBe('A');
it('the given binary string is cleaned before conversion', () => {
expect(convertAsciiBinaryToText(' 01000 001garbage')).toBe('A');
});
it('throws an error if the given binary string is not an integer number of complete octets', () => {
expect(() => convertUtf8BinaryToText('010000011')).toThrow('Invalid binary string');
expect(() => convertUtf8BinaryToText('010000011 010000011')).toThrow('Invalid binary string');
expect(() => convertUtf8BinaryToText('1')).toThrow('Invalid binary string');
});
it('throws an error if the given binary string is not valid UTF-8', () => {
expect(() => convertUtf8BinaryToText('11111111')).toThrow();
});
it('the given string is cleaned from prefix before conversion', () => {
expect(convertUtf8BinaryToText('0b01000001')).toBe('A');
expect(convertUtf8BinaryToText('0x41', { base: 16 })).toBe('A');
expect(convertUtf8BinaryToText('0x68 0x65 0x6c 0x6c 0x6f', { base: 16 })).toBe('hello');
expect(convertUtf8BinaryToText('\\x68\\x65\\x6c\\x6c\\x6f', { base: 16 })).toBe('hello');
});
it('works with non-ASCII input', () => {
for (const { text, binary } of utf8Tests) {
const reverted = convertUtf8BinaryToText(binary);
expect(reverted).toBe(text);
}
it('throws an error if the given binary string as no complete octet', () => {
expect(() => convertAsciiBinaryToText('010000011')).toThrow('Invalid binary string');
expect(() => convertAsciiBinaryToText('1')).toThrow('Invalid binary string');
});
});
});
@@ -1,67 +1,22 @@
export { convertTextToUtf8Binary, convertUtf8BinaryToText };
export { convertTextToAsciiBinary, convertAsciiBinaryToText };
export type EncodingBase = 2 | 8 | 10 | 16;
function convertTextToUtf8Binary(text: string, { separator = ' ', base = 2 }: { separator?: string; base?: EncodingBase } = {}): string {
if (!text?.trim()) {
return '';
}
return [...new TextEncoder().encode(text)].map((char) => {
const charInBase = char.toString(base);
if (base === 2) {
return charInBase.padStart(8, '0');
}
if (base === 8) {
return `0${charInBase}`;
}
if (base === 16) {
return charInBase.padStart(2, '0');
}
return charInBase;
}).join(separator);
function convertTextToAsciiBinary(text: string, { separator = ' ' }: { separator?: string } = {}): string {
return text
.split('')
.map(char => char.charCodeAt(0).toString(2).padStart(8, '0'))
.join(separator);
}
function convertUtf8BinaryToText(binary: string, { base = 2 }: { base?: EncodingBase } = {}): string {
if (!binary?.trim()) {
return '';
function convertAsciiBinaryToText(binary: string): string {
const cleanBinary = binary.replace(/[^01]/g, '');
if (cleanBinary.length % 8) {
throw new Error('Invalid binary string');
}
let codepoints: number[] = [];
if (base === 2) {
const cleanBinary = binary.replace(/0b/g, '').replace(/[^01]/g, '').trim();
if (cleanBinary.length % 8) {
throw new Error('Invalid binary string');
}
codepoints = cleanBinary
.split(/([01]{8})/)
.filter(Boolean)
.map(binary => Number.parseInt(binary, 2));
}
else if (base === 16) {
const cleanBinary = binary.replace(/0x|\\x/g, '').replace(/[^0-9A-Fa-f]/g, '');
if (cleanBinary.length % 2) {
throw new Error('Invalid hexadecimal string');
}
codepoints = cleanBinary
.split(/([0-9A-Fa-f]{2})/)
.filter(Boolean)
.map(binary => Number.parseInt(binary, 16));
}
else {
const cleanBinary = binary.replace(/0o/g, '').replace(/[^\d\s]/g, '');
codepoints = cleanBinary
.split(/\s/)
.filter(Boolean)
.map(binary => Number.parseInt(binary, base));
}
return new TextDecoder(undefined, { fatal: true }).decode(
Uint8Array.from(codepoints),
);
return cleanBinary
.split(/(\d{8})/)
.filter(Boolean)
.map(binary => String.fromCharCode(Number.parseInt(binary, 2)))
.join('');
}
+23 -76
View File
@@ -1,95 +1,42 @@
<script setup lang="ts">
import { type EncodingBase, convertTextToUtf8Binary, convertUtf8BinaryToText } from './text-to-binary.models';
import { convertAsciiBinaryToText, convertTextToAsciiBinary } from './text-to-binary.models';
import { withDefaultOnError } from '@/utils/defaults';
import { useCopy } from '@/composable/copy';
import { isNotThrowing } from '@/utils/boolean';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const base = useQueryParamOrStorage({ name: 'base', storageName: 'txt-bin:base', defaultValue: '2' });
const inputText = ref('');
const binaryFromText = computed(() => convertTextToUtf8Binary(inputText.value, { base: Number(base.value) as EncodingBase }));
const binaryFromText = computed(() => convertTextToAsciiBinary(inputText.value));
const { copy: copyBinary } = useCopy({ source: binaryFromText });
const inputBinary = ref('');
const textFromBinary = computed(() => withDefaultOnError(() => convertUtf8BinaryToText(inputBinary.value, { base: Number(base.value) as EncodingBase }), ''));
const textFromBinary = computed(() => withDefaultOnError(() => convertAsciiBinaryToText(inputBinary.value), ''));
const inputBinaryValidationRules = [
{
validator: (value: string) => isNotThrowing(() => convertUtf8BinaryToText(value)),
message: 'Binary should be a valid UTF-8 binary string with multiples of 8 bits',
validator: (value: string) => isNotThrowing(() => convertAsciiBinaryToText(value)),
message: 'Binary should be a valid ASCII binary string with multiples of 8 bits',
},
];
const { copy: copyText } = useCopy({ source: textFromBinary });
</script>
<template>
<div>
<c-select
v-model:value="base"
label="Conversion Base:"
label-position="left"
mb-2
:options="[
{ value: '2', label: 'Binary' },
{ value: '8', label: 'Octal' },
{ value: '10', label: 'Decimal' },
{ value: '16', label: 'Hexadecimal' },
]"
/>
<c-card title="Text to ASCII binary">
<c-input-text v-model:value="inputText" multiline placeholder="e.g. 'Hello world'" label="Enter text to convert to binary" autosize autofocus raw-text test-id="text-to-binary-input" />
<c-input-text v-model:value="binaryFromText" label="Binary from your text" multiline raw-text readonly mt-2 placeholder="The binary representation of your text will be here" test-id="text-to-binary-output" />
<div mt-2 flex justify-center>
<c-button :disabled="!binaryFromText" @click="copyBinary()">
Copy binary to clipboard
</c-button>
</div>
</c-card>
<c-card title="Text to UTF-8 binary">
<c-input-text
v-model:value="inputText"
multiline
placeholder="e.g. 'Hello world'"
label="Enter text to convert to binary"
autosize
autofocus
raw-text
test-id="text-to-binary-input"
/>
<c-input-text
v-model:value="binaryFromText"
label="Binary from your text"
multiline
raw-text
readonly
mt-2
placeholder="The binary representation of your text will be here"
test-id="text-to-binary-output"
/>
<div mt-2 flex justify-center>
<c-button :disabled="!binaryFromText" @click="copyBinary()">
Copy binary to clipboard
</c-button>
</div>
</c-card>
<c-card title="UTF-8 binary to text">
<c-input-text
v-model:value="inputBinary"
multiline
placeholder="e.g. '01001000 01100101 01101100 01101100 01101111'"
label="Enter binary to convert to text"
autosize
raw-text
:validation-rules="inputBinaryValidationRules"
test-id="binary-to-text-input"
/>
<c-input-text
v-model:value="textFromBinary"
label="Text from your binary"
multiline
raw-text
readonly
mt-2
placeholder="The text representation of your binary will be here"
test-id="binary-to-text-output"
/>
<div mt-2 flex justify-center>
<c-button :disabled="!textFromBinary" @click="copyText()">
Copy text to clipboard
</c-button>
</div>
</c-card>
</div>
<c-card title="ASCII binary to text">
<c-input-text v-model:value="inputBinary" multiline placeholder="e.g. '01001000 01100101 01101100 01101100 01101111'" label="Enter binary to convert to text" autosize raw-text :validation-rules="inputBinaryValidationRules" test-id="binary-to-text-input" />
<c-input-text v-model:value="textFromBinary" label="Text from your binary" multiline raw-text readonly mt-2 placeholder="The text representation of your binary will be here" test-id="binary-to-text-output" />
<div mt-2 flex justify-center>
<c-button :disabled="!textFromBinary" @click="copyText()">
Copy text to clipboard
</c-button>
</div>
</c-card>
</template>
@@ -10,18 +10,16 @@ test.describe('Tool - Text to Unicode', () => {
});
test('Text to unicode conversion', async ({ page }) => {
await page.getByTestId('text-to-unicode-input').fill('"it-tools" 文字');
await page.getByTestId('text-to-unicode-input').fill('it-tools');
const unicode = await page.getByTestId('text-to-unicode-output').inputValue();
// eslint-disable-next-line unicorn/escape-case
expect(unicode).toEqual(String.raw`\u0022it-tools\u0022 \u6587\u5b57`);
expect(unicode).toEqual('&#105;&#116;&#45;&#116;&#111;&#111;&#108;&#115;');
});
test('Unicode to text conversion', async ({ page }) => {
// eslint-disable-next-line unicorn/escape-case
await page.getByTestId('unicode-to-text-input').fill(String.raw`\u0022it-tools\u0022 \u6587\u5b57`);
await page.getByTestId('unicode-to-text-input').fill('&#105;&#116;&#45;&#116;&#111;&#111;&#108;&#115;');
const text = await page.getByTestId('unicode-to-text-output').inputValue();
expect(text).toEqual('"it-tools" 文字');
expect(text).toEqual('it-tools');
});
});
@@ -5,18 +5,7 @@ describe('text-to-unicode', () => {
describe('convertTextToUnicode', () => {
it('a text string is converted to unicode representation', () => {
expect(convertTextToUnicode('A')).toBe('&#65;');
expect(convertTextToUnicode('💩 AĀ')).toBe('&#128169;&#32;&#65;&#256;');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'antiuni' })).toBe('\\u1f4a9\\u20\\u41\\u0100');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'css' })).toBe('\\01f4a9\\000020\\000041\\000100');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'htmldec' })).toBe('&#128169;&#32;&#65;&#256;');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'htmlhex' })).toBe('&#x1f4a9;&#x20;&#x41;&#x100;');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'uniplus' })).toBe('U+1f4a9 U+00020 U+00041 U+00100');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'python' })).toBe('\\U1f4a9\\x20\\x41\\u0100');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'js' })).toBe('\\u{1f4a9}\\u0020\\u0041\\u0100');
expect(convertTextToUnicode('💩 AĀ', { encoding: 'utf16' })).toBe('\\ud83d\\udca9\\u0020\\u0041\\u0100');
expect(convertTextToUnicode('💩 hello AĀ', { skipAscii: true })).toBe('&#128169; hello A&#256;');
expect(convertTextToUnicode('linke the string convert to unicode')).toBe(
'&#108;&#105;&#110;&#107;&#101;&#32;&#116;&#104;&#101;&#32;&#115;&#116;&#114;&#105;&#110;&#103;&#32;&#99;&#111;&#110;&#118;&#101;&#114;&#116;&#32;&#116;&#111;&#32;&#117;&#110;&#105;&#99;&#111;&#100;&#101;');
expect(convertTextToUnicode('linke the string convert to unicode')).toBe('&#108;&#105;&#110;&#107;&#101;&#32;&#116;&#104;&#101;&#32;&#115;&#116;&#114;&#105;&#110;&#103;&#32;&#99;&#111;&#110;&#118;&#101;&#114;&#116;&#32;&#116;&#111;&#32;&#117;&#110;&#105;&#99;&#111;&#100;&#101;');
expect(convertTextToUnicode('')).toBe('');
});
});
@@ -24,16 +13,6 @@ describe('text-to-unicode', () => {
describe('convertUnicodeToText', () => {
it('an unicode string is converted to its text representation', () => {
expect(convertUnicodeToText('&#65;')).toBe('A');
expect(convertUnicodeToText('\\u1f4a9\\u20\\u41\\u0100')).toBe('💩 AĀ');
expect(convertUnicodeToText('\\01f4a9\\000020\\000041\\000100')).toBe('💩 AĀ');
expect(convertUnicodeToText('&#128169;&#32;&#65;&#256;')).toBe('💩 AĀ');
expect(convertUnicodeToText('&#x1f4a9;&#x20;&#x41;&#x100;')).toBe('💩 AĀ');
expect(convertUnicodeToText('U+1f4a9 U+00020 U+00041 U+00100')).toBe('💩 AĀ');
expect(convertUnicodeToText('\\U1f4a9\\x20\\x41\\u0100')).toBe('💩 AĀ');
expect(convertUnicodeToText('\\u{1f4a9}\\u0020\\u0041\\u0100')).toBe('💩 AĀ');
expect(convertUnicodeToText('\\ud83d\\udca9\\u0020\\u0041\\u0100')).toBe('💩 AĀ');
expect(convertUnicodeToText('\\01f4a9 AĀ')).toBe('💩 AĀ');
expect(convertUnicodeToText('&#128169; hello A&#256;')).toBe('💩 hello AĀ');
expect(convertUnicodeToText('&#108;&#105;&#110;&#107;&#101;&#32;&#116;&#104;&#101;&#32;&#115;&#116;&#114;&#105;&#110;&#103;&#32;&#99;&#111;&#110;&#118;&#101;&#114;&#116;&#32;&#116;&#111;&#32;&#117;&#110;&#105;&#99;&#111;&#100;&#101;')).toBe('linke the string convert to unicode');
expect(convertUnicodeToText('')).toBe('');
});
@@ -1,66 +1,9 @@
export type Encoding = 'htmldec' | 'htmlhex' | 'uniplus' | 'antiuni' | 'css' | 'python' | 'js' | 'utf16';
const ALL_PRINTABLE_ASCII = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
function convertTextToUnicode(text: string, { encoding = 'htmldec', skipAscii = false }: { encoding?: Encoding; skipAscii?: boolean } = {}): string {
let prefix: (value: number) => string;
let suffix: (value: number) => string = () => '';
let base = 16;
let padding: (value: number) => number = () => 0;
let separator = '';
let codepoints = [...text];
if (encoding === 'htmldec') {
prefix = () => '&#';
base = 10;
suffix = () => ';';
}
else if (encoding === 'htmlhex') {
prefix = () => '&#x';
suffix = () => ';';
}
else if (encoding === 'uniplus') {
prefix = () => 'U+';
padding = () => 5;
separator = ' ';
}
else if (encoding === 'antiuni') {
prefix = () => '\\u';
padding = (value: number) => value < 256 ? 2 : 4;
}
else if (encoding === 'utf16') {
prefix = () => '\\u';
padding = () => 4;
codepoints = text.split('');
}
else if (encoding === 'python') {
prefix = (value: number) => value < 256 ? '\\x' : (value < 65536 ? '\\u' : '\\U');
padding = (value: number) => value < 256 ? 2 : 4;
}
else if (encoding === 'js') {
prefix = (value: number) => value < 65536 ? '\\u' : '\\u{';
suffix = (value: number) => value < 65536 ? '' : '}';
padding = () => 4;
}
else if (encoding === 'css') {
prefix = () => '\\';
padding = () => 6;
}
return codepoints.map((value) => {
if (skipAscii && ALL_PRINTABLE_ASCII.includes(value)) {
return value;
}
const charCode = value.codePointAt(0) || 0xFF;
return `${prefix(charCode)}${charCode.toString(base).padStart(padding(charCode), '0')}${suffix(charCode)}`;
}).join(separator);
function convertTextToUnicode(text: string): string {
return text.split('').map(value => `&#${value.charCodeAt(0)};`).join('');
}
function convertUnicodeToText(unicodeStr: string): string {
return unicodeStr
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(dec))
.replace(/&#[xX]([0-9A-Fa-f]+);/g, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
.replace(/\\u\{([0-9A-Fa-f]+)\}/g, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
.replace(/(?:\\[uUx]|\\|\s*U\+)([0-9A-Fa-f]+)/g, (match, hex) => String.fromCodePoint(Number.parseInt(hex, 16))); // NOSONAR
return unicodeStr.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec));
}
export { convertTextToUnicode, convertUnicodeToText };
+3 -31
View File
@@ -1,46 +1,18 @@
<script setup lang="ts">
import { type Encoding, convertTextToUnicode, convertUnicodeToText } from './text-to-unicode.service';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { convertTextToUnicode, convertUnicodeToText } from './text-to-unicode.service';
import { useCopy } from '@/composable/copy';
const encoding = useQueryParamOrStorage({ name: 'enc', storageName: 'txt-uni:enc', defaultValue: 'htmldec' });
const skipAscii = useQueryParamOrStorage({ name: 'skipAscii', storageName: 'txt-uni:asc', defaultValue: false });
const inputText = ref('');
const unicodeFromText = computed(() => inputText.value.trim() === ''
? ''
: convertTextToUnicode(inputText.value, { encoding: encoding.value as Encoding, skipAscii: skipAscii.value }));
const unicodeFromText = computed(() => inputText.value.trim() === '' ? '' : convertTextToUnicode(inputText.value));
const { copy: copyUnicode } = useCopy({ source: unicodeFromText });
const inputUnicode = ref('');
const textFromUnicode = computed(() => inputUnicode.value.trim() === ''
? ''
: convertUnicodeToText(inputUnicode.value));
const textFromUnicode = computed(() => inputUnicode.value.trim() === '' ? '' : convertUnicodeToText(inputUnicode.value));
const { copy: copyText } = useCopy({ source: textFromUnicode });
</script>
<template>
<c-card title="Text to Unicode">
<c-select
v-model:value="encoding"
label="Unicode encoding"
:options="[
{ value: 'htmldec', label: 'HTML Decimal (&amp;#160;)' },
{ value: 'htmlhex', label: 'HTML Hexadecimal (&amp;#xA0;)' },
{ value: 'uniplus', label: 'U+00A0' },
{ value: 'antiuni', label: '\\u00A0' },
{ value: 'css', label: 'CSS (\\0000A0)' },
{ value: 'python', label: 'Python (\\xA0, \\u00A0, \\U100A0)' },
{ value: 'js', label: 'Python (\\u00A0; \\u{100A0})' },
{ value: 'utf16', label: 'UTF 16 (with surrogates)' },
]"
/>
<n-form-item>
<n-checkbox v-model:checked="skipAscii">
Skip Ascii characters
</n-checkbox>
</n-form-item>
<c-input-text v-model:value="inputText" multiline placeholder="e.g. 'Hello Avengers'" label="Enter text to convert to unicode" autosize autofocus raw-text test-id="text-to-unicode-input" />
<c-input-text v-model:value="unicodeFromText" label="Unicode from your text" multiline raw-text readonly mt-2 placeholder="The unicode representation of your text will be here" test-id="text-to-unicode-output" />
<div mt-2 flex justify-center>