Marijn van Vliet
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Efficient multiplication using left-shift on Ben Eater's 8-bit breadboard computer ###### tags: `8bit` This code and an emulator to run it can be found at: https://github.com/wmvanvliet/8bit ## Slow multiplication In one of his video's, Ben Eater showed us [a program to multiply two numbers](https://youtu.be/Zg1NdPKoosU?t=1971). In short, to multiply $x$ by $y$, you would add $x$ to the result $y$ times, using a loop: ``` ; ; Multiply two numbers using a loop (Ben Eater's design) ; loop: lda prod add x sta prod lda y sub one jz end sta y jmp loop end: lda prod out hlt one: db 1 x: db 5 y: db 7 prod: db 0 ``` If we were to compute $17 \times 15$ in this manner, the loop would iterate 15 times. Can we do better? ## A better multiplication algorithm Computer science text-books will tell you that multiplication is usually performed using a ["shift and add"](https://en.wikipedia.org/wiki/Multiplication_algorithm#Usage_in_computers) algorithm, which is the binary version of the "long multiplication" method of multiplying you may have learned in elementary school. This is how one would compute $17 \times 15$ in binary using this method: ``` 00010001 00001111 ------------------- x 00010001 00010001 00010001 00010001 00000000 00000000 00000000 00000000 ------------------- + 000000011111111 ``` At least, that is how we were taught in Dutch elementary schools: multiply with the least significant digit first. According to Wikipedia, in German schools, they multiply using the most significant digit first: ``` 00010001 x 00001111 ------------------- 00000000 00000000 00000000 00000000 00010001 00010001 00010001 00010001 ------------------ + 000000011111111 ``` As it turns out, the German method is more suited to our computer architecture, so we'll be using that. At any rate, this method is much faster, as it always loops 8 times (given our 8-bit numbers). As the multiplication examples show, during an iteration of the loop, we only do three things with the binary numbers: 1. left-shifting the intermediate result 2. determining whether the next most-significant bit of $y$ is a 1 or 0 3. adding $x$ to the intermediate result if it was a 1 Our computer can do all of those things! ## Left-shift without a left-shift instruction But Marijn, we don't have a left-shift instruction! Oh, but we do. Sort of. A number added to itself will left-shift that number: ``` 10011101 10011101 ---------- + 1 00111010 (carry flag is set) ``` Easy enough to create a left-shift instruction by modifying the microcode, but even in the original architecture, we can left-shift a number at a memory location like this: ``` lda x ; load memory contents at address 'x' into A add x ; add memory contents at address 'x' to A sta x ; store A into memory at address 'x' x: db 157 ; store a literal '157' at this address ``` ## Writing a fast multiplication program When we left-shift a number, the carry-flag will tell us whether we just shifted a 1 or 0 out of the register, so we can use the `jc` instruction to either add $x$ to the intermediate result or not. Here's what I came up with, given the 16-bytes of memory that we have. There's not enough room for a counter to properly terminate the program after 8 iterations, so we'll just keep on running, but the output will keep displaying the proper result: ``` ; ; Multiply two numbers (x and y) using left-shift ; loop: lda y ; Step 1: look at the most-significant bit of y add y ; Left-shift y, sets the carry flag if MSB was a 1 sta y ; Store y with the MSB removed lda prod ; Load intermediate result (the product) jc add_x ; Step 2: If the MSB was a 1, add x to the intermediate result jmp shift_result ; Else skip over the adding part add_x: add x ; Add x to the intermediate result out ; Output our intermediate result shift_result: sta prod ; Step 3: Left-shift intermediate result add prod ; sta prod ; jmp loop ; Next iteration x: db 17 ; We are computing 17 x 15 y: db 15 ; prod: db 0 ; The (intermediate) result is stored here ``` If you have Python installed, you can [download the code and an emulator](https://github.com/wmvanvliet/8bit) to try it out: ``` python simulator.py example_programs/multiply_shift.asm ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully