Bits of a key and their count

Every key has a code of 8 bits. Shifting the byte left one bit at a time pushes each bit into the carry flag, starting with the top bit, so a loop can read all bits one by one.

What to build

Read one key. Print its code in binary (8 bits, top bit first), a space, and then how many of the 8 bits are 1.

Requirements

  • Print exactly 8 binary digits.
  • Print a single space after the digits.
  • Print the number of 1 bits as one digit.

Input

One character, then Enter.

Output

One line, such as 01000001 2 for A.

Constraints

The character has a code from 20h to 7Eh.

Example

Input:

A

Output:

01000001 2

Why it works

Each SHL moves the top bit out into CF, and ADC adds CF to the character 0 (30h), which gives 1 (31h) exactly when the bit was 1. The same character minus 0 is the bit itself, so adding it to a counter gives the number of 1 bits. A byte has at most 8 ones, so a single digit is enough.

Examples

Example 1 · Input
A
Expected output
01000001 2
Example 2 · Input
z
Expected output
01111010 5

Hints

Hint 1

Keep the key in BL. Shift it left one bit at a time with SHL BL, 1: the top bit goes into CF.

Hint 2

MOV DL, '0' then ADC DL, 0 turns CF into the character '0' or '1'. Print DL.

Hint 3

To count the ones, add DL − '0' to a counter before you print: MOV AL, DL, SUB AL, '0', ADD BH, AL (the counter). Print the counter at the end with ADD '0'.

Solution

Show one correct solution (try it yourself first)
; Bits of a key and their count
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
    MOV AH, 1
    INT 21H
    MOV BL, AL
    MOV BH, 0           ; the number of 1 bits
    MOV CX, 8
NEXTBIT:
    MOV DL, '0'
    SHL BL, 1           ; the top bit goes into CF
    ADC DL, 0           ; '0' or '1'
    MOV AL, DL
    SUB AL, '0'
    ADD BH, AL          ; count it
    MOV AH, 2
    INT 21H             ; print the bit
    LOOP NEXTBIT
    MOV DL, ' '
    INT 21H
    MOV DL, BH
    ADD DL, '0'
    INT 21H
    MOV AH, 4CH
    INT 21H
MAIN ENDP
END MAIN

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Bits: logic, shifts and rotates →