Base Conversion


Synopsis

(std-num->hex <int>) integer -> hexadecimal string

(std-hex->num <str>) hexadecimal string -> integer

(std-num->bin <int>) integer -> bitvector (list of 0 or 1)

(std-bin->num <intlst>) bitvector -> integer

(std-num->oct <int>) integer -> octal string

(std-oct->num <str>) octal string -> integer

Description

These base conversion functions convert from and to decimal integer values (num) supporting the bases 10, 8, 2 and 16.

Hexadecimal numbers (base 16) and octal numbers (base 8) are represented as strings:

Accepted are strings of the form
"0xAA" - "0x" prefix allowed with hex numbers.

"2A" - uppercase

"000a" - lowercase with optional "0" prefixes.


Returned is the shortest string in uppercase as in the form
"2A" - uppercase with hex numbers and

"12","227" - with octal numbers.

(std-num->bin) and (std-bin->num) convert from/to integer "bitfields" or "bitvectors", a list of 0 or 1 representating the two's complement to a decimal number. (base 2)

(std-num->bin) converts a number to a "bitvector", a list all set (1) bits, but not bitvalues, in comparison to (std-bitlist). Leading zero bits are omitted. See the example to provide them when needed.

Examples

(std-num->hex 10)	=> "A"
(std-hex->num "A")	=> 10
(std-hex->num "FFFF")	=> 65535
(std-num->bin 10)	=> (1 0 1 0)
(std-bin->num '(1 0))	=> 2
(std-num->oct 10)	=> "12"
(std-num->oct 151)	=> "227"
(std-oct->num "10")	=> 8

;;; we might need for every char each bit (huffman decoding)

;;; (std-num->bin 10) => (1 0 1 0)

;;; but we might need (0 0 0 0 1 0 1 0) instead:

(defun char->bits (char / bits)
  (if (setq bits (std-num->bin char))
    (progn
      (while (< (length bits) 8)
        (setq bits (cons 0 bits)))
      bits)))

Arguments

int: A integer number, no real allowed.

str: A string representing a hexadecimal number or octal number. Accepted are "0x" or "0" prefixes

intlst: A list of 0 or 1 numbers representing a bitvector.

Return Value

xxx-> hex returns the shortest uppercase string,

xxx->num returns an signed long integer or real if the integer range is too small
[-2,147,483,646 - 2,147,483,647]

xxx->bin returns the shortest list of bits (0 or 1). Omits leading zero bits

xxx->oct returns the shortest octal string.

Side Effects

None.

Module

(std-require 'STDMATH)

Defined in STDMATH