A converter tool: text in six encodings, hex, binary, decimal, octal, Base64; 8/16/32-bit words either byte order; Tools menu in the top bar
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
ef8f97b1c9
commit
6f60462d44
|
|
@ -5813,3 +5813,101 @@ button.tile:hover {
|
|||
.node .pixel-rgb.dark {
|
||||
fill: rgb(0 0 0 / 0.55);
|
||||
}
|
||||
|
||||
/* Converter */
|
||||
.modal.convert {
|
||||
width: min(860px, 100%);
|
||||
}
|
||||
|
||||
.convert-opts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 18px;
|
||||
margin: 10px 0 12px;
|
||||
}
|
||||
|
||||
.convert-opts label > span {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.convert-in .seg {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.convert-text {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.convert-error {
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.convert-outs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.convert-out {
|
||||
min-width: 0;
|
||||
padding: 6px 8px 8px;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.convert-out-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.convert-out-head .hint {
|
||||
margin: 0;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.convert-value {
|
||||
max-height: 120px;
|
||||
overflow: auto;
|
||||
margin-top: 4px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.convert-table-wrap {
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.convert-table {
|
||||
width: 100%;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.convert-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--panel);
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.convert-table th,
|
||||
.convert-table td {
|
||||
padding: 2px 10px 2px 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,5 +84,6 @@ watch(
|
|||
<EditorFaceDialog v-if="ed.dialog.value === 'face'" />
|
||||
<EditorLibraryDialog v-if="ed.dialog.value === 'library'" />
|
||||
<EditorLibraryPublishDialog v-if="ed.dialog.value === 'library-publish'" />
|
||||
<EditorConvertDialog v-if="ed.dialog.value === 'convert'" />
|
||||
</div>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,144 @@
|
|||
<script setup lang="ts">
|
||||
// The converter: write text, hex, binary, decimal, octal or Base64 and read
|
||||
// it in every other form at once, byte by byte (or word by word) below.
|
||||
import {
|
||||
charLabel,
|
||||
ENCODING_NAMES,
|
||||
ENCODINGS,
|
||||
FORMAT_NAMES,
|
||||
FORMATS,
|
||||
formatAs,
|
||||
parseAs,
|
||||
signed,
|
||||
toWords,
|
||||
type ConvertOptions,
|
||||
type Format,
|
||||
type WordBits,
|
||||
} from '~/lib/convert'
|
||||
|
||||
const ed = useEditor()
|
||||
const close = () => (ed.dialog.value = null)
|
||||
|
||||
const KEY = 'logigate:convert'
|
||||
function load(): { input: string; from: Format; opts: ConvertOptions } {
|
||||
try {
|
||||
const s = JSON.parse(localStorage.getItem(KEY) ?? '')
|
||||
if (s && typeof s.input === 'string' && FORMATS.includes(s.from)) return s
|
||||
} catch {}
|
||||
return { input: 'Hello!', from: 'text', opts: { enc: 'utf8', word: 8, endian: 'big' } }
|
||||
}
|
||||
const start = load()
|
||||
const input = ref(start.input)
|
||||
const from = ref<Format>(start.from)
|
||||
const opts = reactive<ConvertOptions>({ ...start.opts })
|
||||
watch([input, from, opts], () => {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify({ input: input.value, from: from.value, opts }))
|
||||
} catch {}
|
||||
})
|
||||
|
||||
const bytes = computed(() => parseAs(input.value, from.value, opts))
|
||||
const outputs = computed(() =>
|
||||
FORMATS.filter(f => f !== from.value).map(f => {
|
||||
const b = bytes.value
|
||||
return { f, res: b.ok ? formatAs(b.value, f, opts) : null }
|
||||
}),
|
||||
)
|
||||
const words = computed(() => (bytes.value.ok ? toWords(bytes.value.value, opts) : []))
|
||||
const ROWS = 256
|
||||
/** A word as a character, where a word is one character of the encoding (a UTF-8 byte above 7F is only part of one). */
|
||||
const charOf = (v: number) => {
|
||||
const { enc, word, endian } = opts
|
||||
if (word === 8 && (enc === 'ascii' || enc === 'latin1' || (enc === 'utf8' && v < 0x80))) return charLabel(v)
|
||||
if (word === 16 && (enc === 'utf16le' ? endian === 'little' : enc === 'utf16be' && endian === 'big')) return charLabel(v)
|
||||
if (word === 32 && enc === 'utf32be' && endian === 'big') return charLabel(v)
|
||||
return '·'
|
||||
}
|
||||
|
||||
/** Takes an output as the new input. */
|
||||
function use(f: Format, text: string) {
|
||||
from.value = f
|
||||
input.value = text
|
||||
}
|
||||
const WORDS: WordBits[] = [8, 16, 32]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="modal-backdrop" @click.self="close">
|
||||
<div class="modal convert" role="dialog" aria-labelledby="convert-title">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<h2 id="convert-title">Converter</h2>
|
||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||
</div>
|
||||
<p class="hint">Write in one form, read it in all others. Hex and binary take 0x and 0b, spaces and commas, or one long run of digits.</p>
|
||||
|
||||
<div class="convert-opts">
|
||||
<label>
|
||||
<span>Text encoding</span>
|
||||
<select v-model="opts.enc" class="tb-select">
|
||||
<option v-for="e in ENCODINGS" :key="e" :value="e">{{ ENCODING_NAMES[e] }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Word</span>
|
||||
<div class="seg">
|
||||
<button v-for="w in WORDS" :key="w" :class="{ active: opts.word === w }" @click="opts.word = w">{{ w }} bits</button>
|
||||
</div>
|
||||
</label>
|
||||
<label v-if="opts.word > 8">
|
||||
<span>Byte order</span>
|
||||
<div class="seg">
|
||||
<button :class="{ active: opts.endian === 'big' }" title="Highest byte first" @click="opts.endian = 'big'">Big-endian</button>
|
||||
<button :class="{ active: opts.endian === 'little' }" title="Lowest byte first" @click="opts.endian = 'little'">Little-endian</button>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="convert-in">
|
||||
<div class="seg">
|
||||
<button v-for="f in FORMATS" :key="f" :class="{ active: from === f }" @click="from = f">{{ FORMAT_NAMES[f] }}</button>
|
||||
</div>
|
||||
<textarea v-model="input" class="field-input convert-text" rows="3" spellcheck="false" :placeholder="`${FORMAT_NAMES[from]} here`" />
|
||||
<p v-if="!bytes.ok" class="convert-error">{{ bytes.error }}</p>
|
||||
<p v-else class="hint">{{ bytes.value.length }} bytes · {{ words.length }} {{ opts.word }}-bit words</p>
|
||||
</div>
|
||||
|
||||
<div class="convert-outs">
|
||||
<div v-for="o in outputs" :key="o.f" class="convert-out">
|
||||
<div class="convert-out-head">
|
||||
<span>{{ FORMAT_NAMES[o.f] }}</span>
|
||||
<span v-if="o.res?.ok && o.res.note" class="hint">{{ o.res.note }}</span>
|
||||
<span class="grow" />
|
||||
<template v-if="o.res?.ok">
|
||||
<button class="icon-btn" title="Copy" @click="ed.copyText(o.res.value, `${FORMAT_NAMES[o.f]} copied`)"><Icon name="lucide:copy" class="size-3.5" /></button>
|
||||
<button class="icon-btn" title="Write in this form from here on" @click="use(o.f, o.res.value)"><Icon name="lucide:arrow-up" class="size-3.5" /></button>
|
||||
</template>
|
||||
</div>
|
||||
<pre class="convert-value">{{ o.res ? (o.res.ok ? o.res.value : o.res.error) : '' }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="words.length">
|
||||
<h3>Word by word</h3>
|
||||
<div class="convert-table-wrap">
|
||||
<table class="convert-table tabular-nums">
|
||||
<thead>
|
||||
<tr><th>#</th><th>Hex</th><th>Binary</th><th>Decimal</th><th>Signed</th><th>Character</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(v, i) in words.slice(0, ROWS)" :key="i">
|
||||
<td>{{ i }}</td>
|
||||
<td>{{ v.toString(16).toUpperCase().padStart(opts.word / 4, '0') }}</td>
|
||||
<td>{{ v.toString(2).padStart(opts.word, '0') }}</td>
|
||||
<td>{{ v }}</td>
|
||||
<td>{{ signed(v, opts.word) }}</td>
|
||||
<td>{{ charOf(v) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-if="words.length > ROWS" class="hint">and {{ words.length - ROWS }} more</p>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -41,6 +41,8 @@ const ACTIONS: Action[] = [
|
|||
run: () => ed.packageSelected('Part'),
|
||||
},
|
||||
{ id: 'find', label: 'Find anything in the project', icon: 'lucide:search', keys: 'Ctrl+F', aka: 'search where used', run: () => (ed.dialog.value = 'search') },
|
||||
{ id: 'analyzer', label: 'Logic analyzer', icon: 'lucide:activity', aka: 'waveform signals scope trace timing', run: () => (ed.analyzerOpen.value = true) },
|
||||
{ id: 'convert', label: 'Converter: text, hex, binary, decimal', icon: 'lucide:arrow-left-right', aka: 'ascii utf8 unicode base64 octal encode decode', run: () => (ed.dialog.value = 'convert') },
|
||||
{ id: 'table', label: 'Truth table', icon: 'lucide:table', aka: 'test outputs', run: () => (ed.dialog.value = 'table') },
|
||||
{ id: 'fit', label: 'Fit the circuit to the screen', icon: 'lucide:scan', keys: 'F', aka: 'zoom view', run: () => emit('fit') },
|
||||
{ id: 'tidy', label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', aka: 'wires clean route layout', when: () => ed.def.value.wires.length > 0, run: () => ed.tidyAll() },
|
||||
|
|
|
|||
|
|
@ -139,6 +139,13 @@ const linkIcon = computed(() => {
|
|||
}
|
||||
})
|
||||
|
||||
// Tools that work beside the circuit.
|
||||
const toolsMenu = ref<{ x: number; y: number } | null>(null)
|
||||
const toolEntries = computed<MenuEntry[]>(() => [
|
||||
{ label: 'Logic analyzer', icon: 'lucide:activity', checked: ed.analyzerOpen.value, note: 'signals over time', run: () => (ed.analyzerOpen.value = !ed.analyzerOpen.value) },
|
||||
{ label: 'Converter…', icon: 'lucide:arrow-left-right', note: 'text, hex, binary', run: () => (ed.dialog.value = 'convert') },
|
||||
])
|
||||
|
||||
// The names folded into "…": each leads back to it.
|
||||
const foldMenu = ref<{ x: number; y: number } | null>(null)
|
||||
const foldEntries = computed<MenuEntry[]>(() => crumbs.value.folded.map(p => ({ label: p.name, icon: 'lucide:box', run: () => ed.goTo(p.i) })))
|
||||
|
|
@ -252,9 +259,10 @@ const moreEntries = computed<MenuEntry[]>(() => {
|
|||
<select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock">
|
||||
<option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option>
|
||||
</select>
|
||||
<button class="bar-btn" :class="{ active: ed.analyzerOpen.value }" title="Logic analyzer: watched signals over time" @click="ed.analyzerOpen.value = !ed.analyzerOpen.value">
|
||||
<Icon name="lucide:activity" class="size-4" />
|
||||
<button class="bar-btn" :class="{ active: ed.analyzerOpen.value, open: !!toolsMenu }" title="Tools: logic analyzer, converter, assembler" @click="toolsMenu = toolsMenu ? null : below($event)">
|
||||
<Icon name="lucide:wrench" class="size-4" />
|
||||
</button>
|
||||
<EditorContextMenu v-if="toolsMenu" :x="toolsMenu.x" :y="toolsMenu.y" :entries="toolEntries" @close="toolsMenu = null" />
|
||||
<span v-if="hasClock" class="cycles tabular-nums" title="Clock cycles since this circuit was opened">{{ ed.cycles.value.toLocaleString() }} ticks</span>
|
||||
<span class="status" :class="ed.status.value" :title="ed.status.value === 'oscillating' ? 'A loop keeps flipping and never settles (e.g. a NOT feeding itself)' : 'Simulation state'">
|
||||
<span class="dot" />{{ statusText }}
|
||||
|
|
|
|||
|
|
@ -175,7 +175,7 @@ function create() {
|
|||
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
|
||||
const labelFocus = ref(0)
|
||||
const showHelp = ref(false)
|
||||
const dialog = ref<null | 'connector' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face' | 'library' | 'library-publish'>(null)
|
||||
const dialog = ref<null | 'connector' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face' | 'library' | 'library-publish' | 'convert' | 'asm'>(null)
|
||||
/** The component whose box is being drawn in the face designer. */
|
||||
const faceFor = ref<string | null>(null)
|
||||
function designFace(defId: string) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,203 @@
|
|||
// The converter tool: text, hex, binary, decimal, octal and Base64 into one
|
||||
// another. Everything goes through bytes: text by its encoding, numbers as
|
||||
// words of 8, 16 or 32 bits (several bytes each in big- or little-endian).
|
||||
|
||||
export const FORMATS = ['text', 'hex', 'bin', 'dec', 'oct', 'base64'] as const
|
||||
export type Format = (typeof FORMATS)[number]
|
||||
export const FORMAT_NAMES: Record<Format, string> = { text: 'Text', hex: 'Hex', bin: 'Binary', dec: 'Decimal', oct: 'Octal', base64: 'Base64' }
|
||||
|
||||
export const ENCODINGS = ['utf8', 'ascii', 'latin1', 'utf16le', 'utf16be', 'utf32be'] as const
|
||||
export type Encoding = (typeof ENCODINGS)[number]
|
||||
export const ENCODING_NAMES: Record<Encoding, string> = {
|
||||
utf8: 'UTF-8',
|
||||
ascii: 'ASCII (7 bits)',
|
||||
latin1: 'Latin-1 (ISO 8859-1)',
|
||||
utf16le: 'UTF-16 little-endian',
|
||||
utf16be: 'UTF-16 big-endian',
|
||||
utf32be: 'UTF-32 big-endian',
|
||||
}
|
||||
|
||||
export type WordBits = 8 | 16 | 32
|
||||
export interface ConvertOptions {
|
||||
enc: Encoding
|
||||
word: WordBits
|
||||
endian: 'big' | 'little'
|
||||
}
|
||||
|
||||
export type Result<T> = { ok: true; value: T; note?: string } | { ok: false; error: string }
|
||||
|
||||
// ── Text ⇄ bytes ─────────────────────────────────────────────────────
|
||||
|
||||
export function encodeText(s: string, enc: Encoding): Result<Uint8Array> {
|
||||
const out: number[] = []
|
||||
const cps = [...s].map(c => c.codePointAt(0)!)
|
||||
switch (enc) {
|
||||
case 'utf8':
|
||||
return { ok: true, value: new TextEncoder().encode(s) }
|
||||
case 'ascii':
|
||||
case 'latin1': {
|
||||
const max = enc === 'ascii' ? 0x7f : 0xff
|
||||
const bad = cps.findIndex(c => c > max)
|
||||
if (bad >= 0) return { ok: false, error: `"${String.fromCodePoint(cps[bad]!)}" (character ${bad + 1}) has no code in ${ENCODING_NAMES[enc]}` }
|
||||
return { ok: true, value: Uint8Array.from(cps) }
|
||||
}
|
||||
case 'utf16le':
|
||||
case 'utf16be':
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const u = s.charCodeAt(i)
|
||||
if (enc === 'utf16le') out.push(u & 0xff, u >> 8)
|
||||
else out.push(u >> 8, u & 0xff)
|
||||
}
|
||||
return { ok: true, value: Uint8Array.from(out) }
|
||||
case 'utf32be':
|
||||
for (const c of cps) out.push((c >>> 24) & 0xff, (c >>> 16) & 0xff, (c >>> 8) & 0xff, c & 0xff)
|
||||
return { ok: true, value: Uint8Array.from(out) }
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeText(b: Uint8Array, enc: Encoding): Result<string> {
|
||||
switch (enc) {
|
||||
case 'utf8': {
|
||||
const text = new TextDecoder('utf-8').decode(b)
|
||||
return { ok: true, value: text, ...(text.includes('<27>') ? { note: 'Some bytes are not valid UTF-8 (shown as <20>)' } : {}) }
|
||||
}
|
||||
case 'ascii':
|
||||
case 'latin1': {
|
||||
const bad = enc === 'ascii' && b.some(x => x > 0x7f)
|
||||
let text = ''
|
||||
for (const x of b) text += enc === 'ascii' && x > 0x7f ? '<27>' : String.fromCharCode(x)
|
||||
return { ok: true, value: text, ...(bad ? { note: 'Bytes above 7F are not ASCII (shown as <20>)' } : {}) }
|
||||
}
|
||||
case 'utf16le':
|
||||
case 'utf16be': {
|
||||
let text = ''
|
||||
for (let i = 0; i + 1 < b.length; i += 2) text += String.fromCharCode(enc === 'utf16le' ? b[i]! | (b[i + 1]! << 8) : (b[i]! << 8) | b[i + 1]!)
|
||||
return { ok: true, value: text, ...(b.length % 2 ? { note: 'The last byte is half a character' } : {}) }
|
||||
}
|
||||
case 'utf32be': {
|
||||
let text = ''
|
||||
let bad = false
|
||||
for (let i = 0; i + 3 < b.length; i += 4) {
|
||||
const c = ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0
|
||||
if (c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff)) {
|
||||
bad = true
|
||||
text += '<27>'
|
||||
} else text += String.fromCodePoint(c)
|
||||
}
|
||||
return { ok: true, value: text, ...(bad || b.length % 4 ? { note: 'Some bytes are not whole UTF-32 characters' } : {}) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Words ⇄ bytes ────────────────────────────────────────────────────
|
||||
|
||||
/** Bytes as words; a last word short of bytes is filled with zeros. */
|
||||
export function toWords(b: Uint8Array, o: Pick<ConvertOptions, 'word' | 'endian'>): number[] {
|
||||
const n = o.word / 8
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < b.length; i += n) {
|
||||
let v = 0
|
||||
for (let k = 0; k < n; k++) {
|
||||
const byte = b[i + k] ?? 0
|
||||
v += byte * 2 ** (8 * (o.endian === 'big' ? n - 1 - k : k))
|
||||
}
|
||||
out.push(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function fromWords(words: number[], o: Pick<ConvertOptions, 'word' | 'endian'>): Uint8Array {
|
||||
const n = o.word / 8
|
||||
const out = new Uint8Array(words.length * n)
|
||||
words.forEach((v, i) => {
|
||||
for (let k = 0; k < n; k++) {
|
||||
const byte = Math.floor(v / 2 ** (8 * k)) & 0xff
|
||||
out[i * n + (o.endian === 'big' ? n - 1 - k : k)] = byte
|
||||
}
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// ── Number formats ───────────────────────────────────────────────────
|
||||
|
||||
const RADIX: Record<'hex' | 'bin' | 'dec' | 'oct', number> = { hex: 16, bin: 2, dec: 10, oct: 8 }
|
||||
const DIGITS: Record<'hex' | 'bin' | 'dec' | 'oct', RegExp> = { hex: /^[0-9a-f]+$/i, bin: /^[01]+$/, dec: /^\d+$/, oct: /^[0-7]+$/ }
|
||||
|
||||
/** Digits one word takes in a format with a fixed width (hex and binary). */
|
||||
const wordDigits = (fmt: 'hex' | 'bin', word: WordBits) => (fmt === 'hex' ? word / 4 : word)
|
||||
|
||||
/** Words written in a number format: separated by spaces, commas or new lines; 0x, 0b, 0o prefixes are fine. A long hex or binary run is several words. */
|
||||
export function parseWords(input: string, fmt: 'hex' | 'bin' | 'dec' | 'oct', word: WordBits): Result<number[]> {
|
||||
const out: number[] = []
|
||||
const max = 2 ** word
|
||||
for (const raw of input.split(/[\s,;]+/).filter(Boolean)) {
|
||||
const t = raw.replace(fmt === 'hex' ? /^(0x|\$|#)|h$/gi : fmt === 'bin' ? /^0b|b$/gi : fmt === 'oct' ? /^0o/i : /^$/, '').replace(/_/g, '')
|
||||
if (!DIGITS[fmt].test(t)) return { ok: false, error: `"${raw}" is not ${fmt === 'hex' ? 'hex' : fmt === 'bin' ? 'binary' : fmt === 'dec' ? 'a decimal number' : 'octal'}` }
|
||||
if ((fmt === 'hex' || fmt === 'bin') && t.length > wordDigits(fmt, word)) {
|
||||
const d = wordDigits(fmt, word)
|
||||
if (t.length % d) return { ok: false, error: `"${raw}" is ${t.length} digits: not a whole number of ${word}-bit words (${d} digits each)` }
|
||||
for (let i = 0; i < t.length; i += d) out.push(parseInt(t.slice(i, i + d), RADIX[fmt]))
|
||||
continue
|
||||
}
|
||||
const v = parseInt(t, RADIX[fmt])
|
||||
if (v >= max) return { ok: false, error: `"${raw}" does not fit in ${word} bits (up to ${max - 1})` }
|
||||
out.push(v)
|
||||
}
|
||||
return { ok: true, value: out }
|
||||
}
|
||||
|
||||
export function formatWords(words: number[], fmt: 'hex' | 'bin' | 'dec' | 'oct', word: WordBits): string {
|
||||
return words
|
||||
.map(v => {
|
||||
const s = v.toString(RADIX[fmt])
|
||||
return fmt === 'hex' ? s.toUpperCase().padStart(word / 4, '0') : fmt === 'bin' ? s.padStart(word, '0') : s
|
||||
})
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
// ── Base64 ───────────────────────────────────────────────────────────
|
||||
|
||||
export function toBase64(b: Uint8Array): string {
|
||||
let s = ''
|
||||
for (const x of b) s += String.fromCharCode(x)
|
||||
return btoa(s)
|
||||
}
|
||||
|
||||
export function fromBase64(input: string): Result<Uint8Array> {
|
||||
const t = input.replace(/\s+/g, '').replace(/-/g, '+').replace(/_/g, '/')
|
||||
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(t)) return { ok: false, error: 'Not Base64 (A–Z, a–z, 0–9, +, / and = at the end)' }
|
||||
try {
|
||||
const s = atob(t.padEnd(Math.ceil(t.length / 4) * 4, '='))
|
||||
return { ok: true, value: Uint8Array.from(s, c => c.charCodeAt(0)) }
|
||||
} catch {
|
||||
return { ok: false, error: 'Not Base64' }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Any format ⇄ bytes ───────────────────────────────────────────────
|
||||
|
||||
export function parseAs(input: string, fmt: Format, o: ConvertOptions): Result<Uint8Array> {
|
||||
if (fmt === 'text') return encodeText(input, o.enc)
|
||||
if (fmt === 'base64') return fromBase64(input)
|
||||
const w = parseWords(input, fmt, o.word)
|
||||
return w.ok ? { ok: true, value: fromWords(w.value, o) } : w
|
||||
}
|
||||
|
||||
export function formatAs(b: Uint8Array, fmt: Format, o: ConvertOptions): Result<string> {
|
||||
if (fmt === 'text') return decodeText(b, o.enc)
|
||||
if (fmt === 'base64') return { ok: true, value: toBase64(b) }
|
||||
const note = b.length % (o.word / 8) ? `The last word is filled up with zero bytes` : undefined
|
||||
return { ok: true, value: formatWords(toWords(b, o), fmt, o.word), ...(note ? { note } : {}) }
|
||||
}
|
||||
|
||||
/** A word as a signed number (two's complement). */
|
||||
export const signed = (v: number, word: WordBits) => (v >= 2 ** (word - 1) ? v - 2 ** word : v)
|
||||
|
||||
/** How a byte or character shows in a table: control characters by name. */
|
||||
export function charLabel(code: number): string {
|
||||
const NAMES: Record<number, string> = { 0: 'NUL', 7: 'BEL', 8: 'BS', 9: 'TAB', 10: 'LF', 13: 'CR', 27: 'ESC', 32: 'space', 127: 'DEL' }
|
||||
if (NAMES[code]) return NAMES[code]!
|
||||
if (code < 32 || (code >= 0x80 && code < 0xa0)) return `^${code.toString(16).toUpperCase().padStart(2, '0')}`
|
||||
if (code >= 0xd800 && code <= 0xdfff) return '·'
|
||||
return code <= 0x10ffff ? String.fromCodePoint(code) : '·'
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { charLabel, ENCODINGS, formatAs, FORMATS, parseAs, parseWords, signed, type ConvertOptions } from '../app/lib/convert'
|
||||
|
||||
const o: ConvertOptions = { enc: 'utf8', word: 8, endian: 'big' }
|
||||
const conv = (input: string, from: (typeof FORMATS)[number], to: (typeof FORMATS)[number], opts: Partial<ConvertOptions> = {}) => {
|
||||
const b = parseAs(input, from, { ...o, ...opts })
|
||||
if (!b.ok) throw new Error(b.error)
|
||||
const out = formatAs(b.value, to, { ...o, ...opts })
|
||||
if (!out.ok) throw new Error(out.error)
|
||||
return out.value
|
||||
}
|
||||
|
||||
describe('converter', () => {
|
||||
it('text to hex, binary, decimal, octal and Base64, and back', () => {
|
||||
expect(conv('Hi!', 'text', 'hex')).toBe('48 69 21')
|
||||
expect(conv('Hi!', 'text', 'bin')).toBe('01001000 01101001 00100001')
|
||||
expect(conv('Hi!', 'text', 'dec')).toBe('72 105 33')
|
||||
expect(conv('Hi!', 'text', 'oct')).toBe('110 151 41')
|
||||
expect(conv('Hi!', 'text', 'base64')).toBe('SGkh')
|
||||
for (const f of FORMATS) expect(conv(conv('Hällo €', 'text', f), f, 'text')).toBe('Hällo €')
|
||||
})
|
||||
|
||||
it('every encoding round-trips what it can encode', () => {
|
||||
for (const enc of ENCODINGS) {
|
||||
const s = enc === 'ascii' ? 'Hello' : enc === 'latin1' ? 'Grüße' : 'Grüße 😀'
|
||||
expect(conv(conv(s, 'text', 'hex', { enc }), 'hex', 'text', { enc })).toBe(s)
|
||||
}
|
||||
expect(conv('Hé', 'text', 'hex', { enc: 'utf16le' })).toBe('48 00 E9 00')
|
||||
expect(conv('😀', 'text', 'hex', { enc: 'utf32be' })).toBe('00 01 F6 00')
|
||||
expect(parseAs('é', 'text', { ...o, enc: 'ascii' }).ok).toBe(false)
|
||||
})
|
||||
|
||||
it('hex and binary accept prefixes, separators and long runs', () => {
|
||||
expect(conv('0x48,0x69 $21', 'hex', 'text')).toBe('Hi!')
|
||||
expect(conv('486921', 'hex', 'dec')).toBe('72 105 33')
|
||||
expect(conv('0b0100_1000', 'bin', 'hex')).toBe('48')
|
||||
expect(parseWords('ABC', 'hex', 8).ok).toBe(false)
|
||||
expect(parseWords('256', 'dec', 8).ok).toBe(false)
|
||||
expect(parseWords('zz', 'hex', 8).ok).toBe(false)
|
||||
})
|
||||
|
||||
it('words of 16 and 32 bits, in either byte order', () => {
|
||||
expect(conv('1234', 'hex', 'hex', { word: 16 })).toBe('1234')
|
||||
expect(conv('1234', 'hex', 'dec', { word: 16 })).toBe('4660')
|
||||
const le = parseAs('1234', 'hex', { ...o, word: 16, endian: 'little' })
|
||||
expect(le.ok && [...le.value]).toEqual([0x34, 0x12])
|
||||
expect(conv('DEADBEEF', 'hex', 'dec', { word: 32 })).toBe('3735928559')
|
||||
expect(conv('Hi!', 'text', 'hex', { word: 16 })).toBe('4869 2100')
|
||||
expect(signed(0xff, 8)).toBe(-1)
|
||||
expect(signed(0x7f, 8)).toBe(127)
|
||||
})
|
||||
|
||||
it('control characters have names', () => {
|
||||
expect(charLabel(10)).toBe('LF')
|
||||
expect(charLabel(65)).toBe('A')
|
||||
expect(charLabel(1)).toBe('^01')
|
||||
})
|
||||
})
|
||||
Loading…
Reference in New Issue