16 bit ASCII to Binary Conversion

Tight_Coder_Ex 0 Tallied Votes 456 Views Share

User can enter an ascii string of up to 48 characters consisting of 1's or 0's, with randomly interspersed whitespace.

IE: 1011111001011110 will be evaulated equally to
[1011][111....cc001cccx01 111hhhh0

Algorithm parses from right to left so will be truncated at 16 position

Purpose is to give all those still programming in 16 bit an example they can learn from and hopefully embellish and post their version

Compile with NASMW -fbin file.asm -ofile.com

		BITS	16

		org	100H

		jmp	Start

	;=============================================================================
  Buffer	db	48			; Maximum allowable input
		times	48	db 0		; Pad buffer with nulls

	;-----------------------------------------------------------------------------
  Start		mov	ah, 9			; Display String
		mov	dx, PrmA
		int	21H			; Display initial prompt

		mov	dx, Buffer		; Point to input buffer
		mov	ax, 0C0AH		; Clear keyboard and get string
		int	21H

	; Determine if user actually enters anything

		push	si
		mov	si, dx
		xor	ax, ax
		inc	si
		mov	al, [si]		; Get number of characters entered
		and	ax, ax
		jnz	.Eval

	; Display prompt of no real meaning

		mov	dx, PrmB
		mov	ah, 9
		int	21H
		jmp	.Fin

	; Begin evaluation of string that contains 0's & 1's with any kind of 
	; embedded whitespace

  .Eval		push	bx
		xor	bx, bx			; Intermidate result
		add	si, ax			; Points to last character of string
		mov	cx, ax			; Countdown to begining of string
		mov	dx, 1			; Initial bit mask
		std				; Decrement index
		inc	cx			; Bump for loops functioning

	; Loop is structured this way so not to exceed 16 bit limit

  .Loop		dec	cx			; Decrement character count
		jz	.Done

		lodsb				; Get byte from string
		xor	al, 30H			; If valid AX will equal 0 or 1
		cmp	al, 1
		ja	.Loop			; otherwise it must be whitespace
		jnz	.L0			; Don't bother setting bit 
		or	bx, dx
  .L0		shl	dx, 1			; Move mask bit to next position
		jnc	.Loop			; All 16 bits evaluated

	; --- NOTE ---
	; Other snippets in this forum will demonstate how to show result
	; in HEX or DECIMAL. At the time of writing these had not been posted yet.

	; Feel free to insert an output routine, the only thing I ask you acknowlege
	; what is mine.

  .Done		mov	ax, bx			; Move result to AX	
		pop	bx
		cld				; Increment index
  .Fin		pop	si	
		ret
	; ____________________________________________________________________________

  PrmA		db	10, 10, 10, 13, 'Please enter string of 0 & 1'
		db	10, 10, 13, 9, '--> $'
  PrmB		db	10, 10, 13, 'Ok <> I am outta here', 10, 10, 13, '$'

Dani AI

Generated

provided a neat, compact routine that converts an ASCII stream of 0/1 characters (with arbitrary whitespace) into a 16‑bit value. The code is fine for quick, in-place use; the notes below clarify exact behavior, highlight pitfalls, and give a small portable parser you can drop into C for testing or adaptation.

Clarifications and gotchas

  • The reference routine walks the string from the right end toward the left, so the rightmost digit in the text becomes bit 0 (LSB).
  • Whitespace is skipped and does not consume a bit position.
  • If more than 16 significant binary digits are present, extra digits are truncated (only the low 16 bits are kept). If you need overflow detection or a different endianness, handle that explicitly.

Portable C parser (MSB-first, left-to-right). Returns false on invalid characters; sets overflow if more than 16 significant bits were seen.

#include <ctype.h>
#include <stdint.h>
#include <stdbool.h>

bool parse_bin16(const char *s, uint16_t *out, bool *overflow) {
    uint32_t acc = 0;
    unsigned bits = 0;
    for (; *s; ++s) {
        unsigned char c = (unsigned char)*s;
        if (isspace(c)) continue;
        if (c != '0' && c != '1') return false; /* invalid */
        acc = (acc << 1) | (c - '0'); /* left-to-right, MSB-first */
        if (++bits > 16) {
            if (overflow) *overflow = true;
            acc &= 0xFFFF;
        }
    }
    if (out) *out = (uint16_t)acc;
    if (overflow && bits <= 16) *overflow = false;
    return true;
}

Quick test cases and tips

  • "1011111001011110" -> 0xBE5E (48734).
  • " 1011 0001 " -> 0xB1 (177).
  • To emulate the original routine's right-to-left behavior, iterate from the string end toward the start or use a mask variable and OR bits as you scan (instead of accumulating with left shifts).
  • Prefer explicit overflow detection instead of silent truncation when correctness matters; add unit tests for inputs with mixed whitespace and invalid chars.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.