Files
it-tools/src/tools/integer-base-converter/bit-fields.model.ts
T
Robert Dobre 4379630758 feat(integer base converter): bit fields (#605)
Read single bits and bit fields (ranges) of the input number:
- positions as a list: 2, 12, 4-7, 7:4 (0 = LSB); invalid, negative,
  duplicate or too large positions are skipped and reported
- interactive bit strip: click to toggle a bit, drag or Shift+click to
  add a field, keyboard navigation with arrow keys
- results table with click to copy, overlap hints and optional field
  values in hex, octal, base64, a custom base and decimal
- positions and selected bases are kept in the URL and local storage
2026-11-29 21:47:18 +01:00

180 lines
6.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export const MAX_BIT_POSITION = 4095;
export interface BitField {
/** Lowest bit position of the field (0 = LSB) */
lo: number;
/** Highest bit position of the field */
hi: number;
/** Index of the token this field was parsed from, see tokenizeBitPositions */
tokenIndex: number;
}
export type IgnoredReason = 'negative' | 'invalid' | 'too-large' | 'duplicate';
export interface IgnoredToken {
token: string;
reason: IgnoredReason;
}
/**
* Splits a list of bit positions into tokens.
* Separators: commas, semicolons and whitespace.
* En/em dashes and minus signs count as "-", so ranges pasted from datasheets work.
* "4 - 7" and "7 : 4" are ranges; "2 -3" is the position 2 and the (negative) token -3.
*/
export function tokenizeBitPositions(text: string): string[] {
return (text ?? '')
.replace(/[‐-―−﹣-]/g, '-')
.replace(/(\d)\s+-\s+(\d)/g, '$1-$2')
.replace(/\s*(:|\.\.)\s*/g, '$1')
.split(/[\s,;]+/)
.filter(Boolean);
}
/**
* Parses bit positions like "2, 12, 4-7, 7:4, 0..3".
* Never throws: invalid tokens are skipped and reported in `ignored`.
*/
export function parseBitPositions(text: string, { maxBitPosition = MAX_BIT_POSITION } = {}) {
const fields: BitField[] = [];
const ignored: IgnoredToken[] = [];
const seen = new Set<string>();
tokenizeBitPositions(text).forEach((token, tokenIndex) => {
let lo: number;
let hi: number;
const range = token.match(/^(\d+)(?:-|:|\.\.)(\d+)$/);
if (/^\d+$/.test(token)) {
lo = hi = Number(token);
} else if (range) {
lo = Math.min(Number(range[1]), Number(range[2]));
hi = Math.max(Number(range[1]), Number(range[2]));
} else {
const isNegative = /^-+\d/.test(token) || /\d(?:-|:|\.\.)-\d/.test(token);
ignored.push({ token, reason: isNegative ? 'negative' : 'invalid' });
return;
}
if (hi > maxBitPosition) {
ignored.push({ token, reason: 'too-large' });
return;
}
const key = `${lo}:${hi}`;
if (seen.has(key)) {
ignored.push({ token, reason: 'duplicate' });
return;
}
seen.add(key);
fields.push({ lo, hi, tokenIndex });
});
return { fields, ignored };
}
export function getBitFieldWidth(field: Pick<BitField, 'lo' | 'hi'>) {
return field.hi - field.lo + 1;
}
export function isSingleBit(field: Pick<BitField, 'lo' | 'hi'>) {
return field.lo === field.hi;
}
export function extractBitField(value: bigint, field: Pick<BitField, 'lo' | 'hi'>): bigint {
const mask = (1n << BigInt(getBitFieldWidth(field))) - 1n;
return (value >> BigInt(field.lo)) & mask;
}
/** Field value in binary, left-padded to the field width */
export function formatBitFieldBinary(value: bigint, field: Pick<BitField, 'lo' | 'hi'>) {
return extractBitField(value, field).toString(2).padStart(getBitFieldWidth(field), '0');
}
export function getBitFieldLabel(field: Pick<BitField, 'lo' | 'hi'>) {
return isSingleBit(field) ? `bit ${field.lo}` : `bits ${field.hi}..${field.lo}`;
}
export function getBitFieldShortLabel(field: Pick<BitField, 'lo' | 'hi'>) {
return isSingleBit(field) ? `${field.lo}` : `${field.hi}..${field.lo}`;
}
/** For each bit position, the indexes (in `fields`) of the fields containing it */
export function getBitCoverage(fields: BitField[]) {
const coverage = new Map<number, number[]>();
fields.forEach((field, index) => {
for (let bit = field.lo; bit <= field.hi; bit++) {
coverage.set(bit, [...(coverage.get(bit) ?? []), index]);
}
});
return coverage;
}
/** Indexes of the other fields sharing at least one bit with fields[index] */
export function getOverlappingFields(fields: BitField[], index: number) {
const { lo, hi } = fields[index];
return fields
.map((other, otherIndex) => ({ other, otherIndex }))
.filter(({ other, otherIndex }) => otherIndex !== index && other.lo <= hi && other.hi >= lo)
.map(({ otherIndex }) => otherIndex);
}
/** Number of bits to draw: whole bytes, at least 8, enough for the value and every selected bit */
export function getDisplayedBitCount(value: bigint, fields: BitField[]) {
const valueBits = value > 0n ? value.toString(2).length : 1;
const selectedBits = fields.reduce((max, field) => Math.max(max, field.hi + 1), 0);
return Math.ceil(Math.max(8, valueBits, selectedBits) / 8) * 8;
}
// Editing helpers: they return the new positions text and keep invalid tokens as they are.
function joinTokens(tokens: (string | null)[]) {
return tokens.filter((token): token is string => token !== null).join(', ');
}
export function removeBitPositionToken(text: string, tokenIndex: number) {
const tokens: (string | null)[] = tokenizeBitPositions(text);
if (tokenIndex >= 0 && tokenIndex < tokens.length) {
tokens[tokenIndex] = null;
}
return joinTokens(tokens);
}
/** Adds the single bit, or removes it if it is already listed as a single bit */
export function toggleBitPosition(text: string, bit: number) {
const existing = parseBitPositions(text).fields.find((field) => field.lo === bit && field.hi === bit);
if (existing) {
return removeBitPositionToken(text, existing.tokenIndex);
}
return joinTokens([...tokenizeBitPositions(text), String(bit)]);
}
/**
* Adds the field from..to, or removes it if it is already listed.
* replaceBit: a single bit to drop at the same time (the start of a Shift+click selection).
*/
export function toggleBitRange(text: string, from: number, to: number, { replaceBit }: { replaceBit?: number } = {}) {
const lo = Math.min(from, to);
const hi = Math.max(from, to);
if (lo === hi) {
return toggleBitPosition(text, lo);
}
const { fields } = parseBitPositions(text);
const tokens: (string | null)[] = tokenizeBitPositions(text);
if (replaceBit !== undefined) {
const single = fields.find((field) => field.lo === replaceBit && field.hi === replaceBit);
if (single) {
tokens[single.tokenIndex] = null;
}
}
const existing = fields.find((field) => field.lo === lo && field.hi === hi);
if (existing) {
tokens[existing.tokenIndex] = null;
} else {
tokens.push(`${lo}-${hi}`);
}
return joinTokens(tokens);
}