zenoZ
    • 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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 期中作業報告 ``` 課程: 系統程序 學生: 史煜疏 ``` ## 使用python 使用匯編語言編寫成機器語言,最後將結果輸出到二進制的文件和輸出結果保存在文件中還有在控制臺進行輸出。 > 講解 ```= # Define opcode and machine code mapping table opcode_table = { "MOV": "8B", "ADD": "03", "SUB": "2B", "MUL": "0F AF", } ``` ### An opcode table (also called an opcode matrix) is a visual representation of all opcodes in an instruction set. It is arranged such that each axis of the table represents an upper or lower nibble, which combined form the full byte of the opcode. Additional opcode tables can exist for additional instructions created using an opcode prefix. > 資料來源:https://en.wikipedia.org/wiki/Opcode_table ## 定義以一個'Assembler'類 這是一個自定義的類 實現滙編器功能 滙編器是將匯編語言轉換成機器碼的工具。 ```= class Assembler: def __init__(self): self.symbol_table = {} self.error_report = [] ``` ### 首先先初始化兩個變量"symbol_table" 和 "error_report", 這倆分別用於儲存符號表和錯誤報告。 ```= def assemble(self, assembly_code, output_file_name): # Clear symbol table and error report self.symbol_table.clear() self.error_report.clear() # Parse assembly code and build symbol table self.build_symbol_table(assembly_code) # Assemble instructions machine_code = self.assemble_instructions(assembly_code) # Optimize instructions self.optimize(machine_code) # Write output file self.write_output_file(output_file_name, machine_code) # Print error report self.print_error_report() ``` ### 'assemble' 是整個滙編器的入口。 接受匯編代碼和輸出文件名為參考。 ```= a def build_symbol_table(self, assembly_code): current_address = 0 lines = assembly_code.split("\n") for line in lines: if line.strip() and not line.strip().startswith(";"): parts = line.split() if parts[0].endswith(":"): label = parts[0].rstrip(":") if label in self.symbol_table: self.error_report.append(f"Duplicated label: {label}") else: self.symbol_table[label] = current_address else: current_address += 1 ``` ### 構建符號表: 'build_symbol_table'用於解析匯編代碼並構建符號表。 ```= def assemble_instructions(self, assembly_code): machine_code = [] lines = assembly_code.split("\n") for line in lines: if line.strip() and not line.strip().startswith(";"): parts = line.split() if parts[0].endswith(":"): continue instruction = parts[0].upper() operands = parts[1:] if instruction in opcode_table: opcode = opcode_table[instruction] machine_code.append(bytes.fromhex(opcode)) for operand in operands: if operand in self.symbol_table: address = self.symbol_table[operand] machine_code.append(address.to_bytes(4, "big")) else: try: value = int(operand) machine_code.append(value.to_bytes(4, "big")) except ValueError: self.error_report.append(f"Invalid operand: {operand}") else: self.error_report.append(f"Invalid instruction: {instruction}") return b"".join(machine_code) ``` ### "assemble_instructions" 用於將匯編語言轉換成機器碼。 ```= def optimize(self, machine_code): # Perform instruction optimization here pass ``` ### 進行代碼優化 'optimize' 用於優化指令 ```= def write_output_file(self, output_file_name, machine_code): with open(output_file_name, "wb") as file: file.write(machine_code) ``` ### 'write_output_file' 將機器碼寫入輸出文件 ```= def print_error_report(self): for error in self.error_report: print(error) ``` ### 'print_error_report' 打印錯誤報告 ```= with open(output_file_name, "rb") as file: machine_code = file.read() print("Machine code:") for i in range(0, len(machine_code), 4): instruction_bytes = machine_code[i:i+4] print(" ".join(f"{byte:02X}" for byte in instruction_bytes)) ``` ### 將生成的機器碼文件, 按照4個字節進行結構 再將 每個字節以十六進行進行打印。 ## 最後輸出結果 ![](https://hackmd.io/_uploads/B1GwULow2.png) #### 這學期的系統程序語言 多數是用C 進行編寫, 而我的C語言較爲不熟悉,所以期末期中作業多用 python進行編寫和測試 。

    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