Compare commits
91 commits
s-branch-2
...
main
Author | SHA1 | Date | |
---|---|---|---|
5d2f58f869 | |||
29f9130a1b | |||
13bb222dd5 | |||
43032540dd | |||
03922c139e | |||
91765f4e0b | |||
6744ea11bc | |||
bbf5197da6 | |||
5eeb46c4b4 | |||
fefb795f80 | |||
13bcfbbafd | |||
a5c9c120ff | |||
f91427d180 | |||
55d79fbe6a | |||
d6ac0d36db | |||
279b278d8f | |||
e606c2cfb3 | |||
f4f4b53f24 | |||
60ebd2b53c | |||
00c58d5d17 | |||
8fbddc4e51 | |||
4e73ae2382 | |||
5bdc322a0f | |||
968890a5fe | |||
7e1ff29eac | |||
86d43c1a66 | |||
18d57aa241 | |||
5d1eb9d981 | |||
1e1c3b9687 | |||
5a2ec831ee | |||
dbabb956d5 | |||
c37a788cbd | |||
9343c63874 | |||
8b43ad81ed | |||
97b27414a7 | |||
c64fe39549 | |||
569b86bfa0 | |||
2a4d95afe8 | |||
badd502331 | |||
de98ad4268 | |||
493d31e3c6 | |||
c51f88103e | |||
0afb3ab4bd | |||
b75a878a7f | |||
e93a242b55 | |||
e7a49b6432 | |||
f13066ce58 | |||
e23eac9996 | |||
98d9bc2db3 | |||
5149846c61 | |||
0755dd4b76 | |||
4ca2829e4e | |||
011d5aded1 | |||
4cab136b7a | |||
a8ced71b76 | |||
951bf4024a | |||
e73f664627 | |||
0b57ac833f | |||
b43a1d3360 | |||
47d2a871e9 | |||
376f2ccf5e | |||
a1b2495e47 | |||
857ebf4a77 | |||
933a52b3a8 | |||
fdc634b589 | |||
b1105e40e8 | |||
e14e8d58e7 | |||
767d49742b | |||
98942630b6 | |||
518399472f | |||
e14d40f9b2 | |||
0a9d5e3313 | |||
6bae8f4e61 | |||
b1be0e02c6 | |||
9ad6f084ca | |||
3d1c20142d | |||
1da275f0f4 | |||
985e8e3558 | |||
db689b25ef | |||
2e60fcd9b8 | |||
116ca4f08a | |||
8e4cd69947 | |||
f6839485d2 | |||
9f7be54f8e | |||
2f320095cd | |||
e68d8a0cb4 | |||
a865f5becb | |||
d309978375 | |||
d46358f2da | |||
6ff1894732 | |||
44e766514e |
102 changed files with 11643 additions and 8 deletions
BIN
ES/Lab/Guidelines_ARM LPC 1768.pdf
Normal file
BIN
ES/Lab/Guidelines_ARM LPC 1768.pdf
Normal file
Binary file not shown.
BIN
ES/Lab/ICT 3143 ESD LAB CCE EVAL. DETAILS.pdf
Normal file
BIN
ES/Lab/ICT 3143 ESD LAB CCE EVAL. DETAILS.pdf
Normal file
Binary file not shown.
BIN
ES/Lab/ICT 3143 ESD LAB LESSON PLAN_signed.pdf
Normal file
BIN
ES/Lab/ICT 3143 ESD LAB LESSON PLAN_signed.pdf
Normal file
Binary file not shown.
BIN
ES/Lab/ICT CCE ESD LAB MANUAL_2025.pdf
Normal file
BIN
ES/Lab/ICT CCE ESD LAB MANUAL_2025.pdf
Normal file
Binary file not shown.
5
ES/Lab/KitTips.md
Normal file
5
ES/Lab/KitTips.md
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
## Switch
|
||||||
|
- PWM -> CN(A/B/C/D) - Shows value on the 7th pin of the connector.
|
||||||
|
|
||||||
|
## General
|
||||||
|
- Long delays are preferred
|
100
ES/Lab/LAB4/ASCIItoHEX.asm
Normal file
100
ES/Lab/LAB4/ASCIItoHEX.asm
Normal file
|
@ -0,0 +1,100 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; ASCIItoHEX.asm - ASCII Hexadecimal String to 32-bit Hexadecimal Conversion
|
||||||
|
; ========================================================================================
|
||||||
|
; This program converts an ASCII string representing hexadecimal digits into a
|
||||||
|
; 32-bit hexadecimal value. It processes each ASCII character, converts it to
|
||||||
|
; its corresponding 4-bit hexadecimal value, and builds the final 32-bit result
|
||||||
|
; by shifting and ORing each nibble into place.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Initialize pointers to source ASCII string and destination for result
|
||||||
|
; 2. Initialize result accumulator (R1) to 0
|
||||||
|
; 3. Process 8 characters (for 32-bit result) in a loop
|
||||||
|
; 4. For each character:
|
||||||
|
; a. Load ASCII character (byte)
|
||||||
|
; b. Check if it's A-F (greater than '9')
|
||||||
|
; c. Convert ASCII digit to 4-bit hexadecimal value
|
||||||
|
; d. Shift current result left by 4 bits
|
||||||
|
; e. OR the new nibble into the result
|
||||||
|
; 5. Store the final 32-bit hexadecimal value
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize pointers and variables
|
||||||
|
; R0 points to the ASCII string source
|
||||||
|
LDR R0, =SRC ; R0 = address of ASCII string
|
||||||
|
|
||||||
|
; R3 points to the destination for the result
|
||||||
|
LDR R3, =DST ; R3 = address of result storage
|
||||||
|
|
||||||
|
; Initialize result accumulator to 0
|
||||||
|
MOV R1, #0 ; R1 = 0 (will hold the final 32-bit result)
|
||||||
|
|
||||||
|
; Set loop counter for 8 characters (8 nibbles = 32 bits)
|
||||||
|
MOV R10, #8 ; R10 = 8 (number of characters to process)
|
||||||
|
|
||||||
|
; Step 2: Main conversion loop
|
||||||
|
UP
|
||||||
|
; Load the next ASCII character (byte) from the string
|
||||||
|
; Post-increment addressing advances R0 to next character
|
||||||
|
LDRB R2, [R0], #1 ; Load byte from [R0] into R2, then R0 = R0 + 1
|
||||||
|
|
||||||
|
; Check if the character is a letter (A-F) or digit (0-9)
|
||||||
|
; Compare with '9' (ASCII 57) - if R2 <= '9', it's a digit
|
||||||
|
CMP R1, #'9' ; Compare R1 with ASCII '9' (Note: should be CMP R2, #'9')
|
||||||
|
BCC DOWN ; If R2 < '9', branch to DOWN (digit 0-9)
|
||||||
|
|
||||||
|
; Handle A-F characters (subtract 7 to convert A-F to 10-15)
|
||||||
|
SUB R2, #7 ; R2 = R2 - 7 (converts 'A' to 10, 'B' to 11, etc.)
|
||||||
|
|
||||||
|
DOWN
|
||||||
|
; Convert ASCII digit to actual hexadecimal value
|
||||||
|
; Subtract ASCII '0' (0x30) to convert '0'-'9' to 0-9
|
||||||
|
SUB R2, #0x30 ; R2 = R2 - 0x30 (ASCII to numeric conversion)
|
||||||
|
|
||||||
|
; Shift the current result left by 4 bits to make room for new nibble
|
||||||
|
LSL R1, #4 ; R1 = R1 << 4 (shift left by 4 bits)
|
||||||
|
|
||||||
|
; OR the new 4-bit value into the result
|
||||||
|
ORR R1, R1, R2 ; R1 = R1 | R2 (insert new nibble)
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
SUBS R10, #1 ; R10 = R10 - 1, set flags for branch condition
|
||||||
|
|
||||||
|
; Branch back to UP if counter is not zero
|
||||||
|
BNE UP ; If R10 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 3: Store the final result
|
||||||
|
; Store the 32-bit hexadecimal value to destination
|
||||||
|
STR R1, [R3] ; Store R1 (final result) to [R3]
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - ASCII Source String and Result Storage
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC contains ASCII string "12AB34CF" (8 characters)
|
||||||
|
; Each character represents a hexadecimal digit:
|
||||||
|
; '1','2' -> digits 0-9
|
||||||
|
; 'A','B','C','F' -> digits 10-15
|
||||||
|
; The string will be converted to: 0x12AB34CF
|
||||||
|
SRC DCB "12AB34CF" ; ASCII string to be converted
|
||||||
|
|
||||||
|
AREA mydata, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; DST - Storage for the final 32-bit hexadecimal result
|
||||||
|
DST DCD 0 ; Space for the converted result
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
93
ES/Lab/LAB4/BCDtoHEX.asm
Normal file
93
ES/Lab/LAB4/BCDtoHEX.asm
Normal file
|
@ -0,0 +1,93 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; BCDtoHEX.asm - Binary Coded Decimal to Hexadecimal Conversion
|
||||||
|
; ========================================================================================
|
||||||
|
; This program converts a BCD (Binary Coded Decimal) value to its equivalent
|
||||||
|
; hexadecimal representation. BCD stores each decimal digit in 4 bits, so a
|
||||||
|
; byte can represent two decimal digits (00-99). The program extracts each
|
||||||
|
; BCD digit and converts the entire BCD number to its decimal equivalent.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Load the BCD value from memory (each byte contains two BCD digits)
|
||||||
|
; 2. Initialize multiplier (R2) to 1 for units place
|
||||||
|
; 3. Process 3 iterations (for 3 BCD digits in the example)
|
||||||
|
; 4. In each iteration:
|
||||||
|
; a. Extract lowest 4 bits (current BCD digit) using AND
|
||||||
|
; b. Multiply digit by current place value and add to result
|
||||||
|
; c. Shift BCD value right by 4 bits to get next digit
|
||||||
|
; d. Multiply place value by 10 for next iteration
|
||||||
|
; 5. Result (R4) contains the decimal equivalent of the BCD number
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize source pointer and load BCD value
|
||||||
|
; R0 points to the BCD value in memory
|
||||||
|
LDR R0, =SRR ; R0 = address of BCD value
|
||||||
|
|
||||||
|
; Set loop counter for 3 digits (processing 12 bits of the 32-bit value)
|
||||||
|
MOV R10, #3 ; R10 = 3 (number of BCD digits to process)
|
||||||
|
|
||||||
|
; Load the BCD value into R1
|
||||||
|
LDR R1, [R0] ; R1 = BCD value (e.g., 0x45 = 0100 0101 BCD)
|
||||||
|
|
||||||
|
; Initialize multiplier for place value (1 for units, 10 for tens, etc.)
|
||||||
|
MOV R2, #1 ; R2 = 1 (initial place value multiplier)
|
||||||
|
|
||||||
|
; Step 2: Main BCD to decimal conversion loop
|
||||||
|
UP
|
||||||
|
; Extract the lowest 4 bits (current BCD digit 0-9)
|
||||||
|
; AND with 0x0F isolates the least significant nibble
|
||||||
|
AND R3, R1, #0x0F ; R3 = R1 & 0x0F (extract BCD digit)
|
||||||
|
|
||||||
|
; Multiply digit by place value and accumulate result
|
||||||
|
; MLA (Multiply Accumulate) computes: R4 = R2 * R3 + R4
|
||||||
|
; This adds the current digit's contribution to the total
|
||||||
|
MLA R4, R2, R3, R4 ; R4 = (R2 * R3) + R4
|
||||||
|
|
||||||
|
; Shift BCD value right by 4 bits to access next digit
|
||||||
|
LSR R1, #4 ; R1 = R1 >> 4 (move to next BCD digit)
|
||||||
|
|
||||||
|
; Prepare multiplier for next place value (multiply by 10)
|
||||||
|
; This sets up R2 for tens, hundreds, etc. in subsequent iterations
|
||||||
|
MOV R5, #0x0A ; R5 = 10 (decimal)
|
||||||
|
MUL R2, R5 ; R2 = R2 * 10 (update place value)
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
SUBS R10, #1 ; R10 = R10 - 1, set flags for branch condition
|
||||||
|
|
||||||
|
; Branch back to UP if counter is not zero
|
||||||
|
BNE UP ; If R10 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 3: Program termination
|
||||||
|
; Note: The result is stored in R4 but never saved to memory
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - BCD Source Value
|
||||||
|
; ========================================================================================
|
||||||
|
; SRR contains a BCD value: 0x45
|
||||||
|
; In BCD format: 0100 0101 = digits 4 and 5
|
||||||
|
; Decimal equivalent: 4*10 + 5 = 45
|
||||||
|
; The program converts this to decimal 45 (though result is never stored)
|
||||||
|
SRR DCD 0x45 ; BCD value to be converted
|
||||||
|
|
||||||
|
AREA mydata, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; SRC - Additional storage (seems unused in this program)
|
||||||
|
SRC DCD 0x45 ; Duplicate of SRR (possibly for testing)
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
92
ES/Lab/LAB4/GCD.asm
Normal file
92
ES/Lab/LAB4/GCD.asm
Normal file
|
@ -0,0 +1,92 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; GCD.asm - Greatest Common Divisor Using Euclidean Algorithm
|
||||||
|
; ========================================================================================
|
||||||
|
; This program implements the Euclidean algorithm to find the Greatest Common
|
||||||
|
; Divisor (GCD) of two numbers. The Euclidean algorithm is based on the principle
|
||||||
|
; that GCD(a, b) = GCD(b, a mod b), and it repeats this process until b = 0.
|
||||||
|
; When b = 0, the GCD is the value of a.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Initialize two numbers in registers R0 and R1 (48 and 18 in this example)
|
||||||
|
; 2. Enter the Euclidean algorithm loop:
|
||||||
|
; a. Compare the two numbers
|
||||||
|
; b. If equal, GCD is found (algorithm complete)
|
||||||
|
; c. If R0 > R1, subtract R1 from R0 (replace larger with difference)
|
||||||
|
; d. If R0 < R1, subtract R0 from R1 (replace larger with difference)
|
||||||
|
; e. Repeat until both numbers are equal
|
||||||
|
; 3. Store the GCD result to memory
|
||||||
|
; 4. Enter infinite loop for program termination
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize the two numbers for GCD calculation
|
||||||
|
; R0 and R1 hold the two numbers to find GCD of
|
||||||
|
MOV r0, #48 ; R0 = 48 (first number)
|
||||||
|
MOV r1, #18 ; R1 = 18 (second number)
|
||||||
|
|
||||||
|
; Step 2: Main Euclidean algorithm loop
|
||||||
|
GCD_Loop
|
||||||
|
; Compare the two numbers to determine which is larger
|
||||||
|
CMP r0, r1 ; Compare R0 and R1, set condition flags
|
||||||
|
|
||||||
|
; If R0 == R1, we have found the GCD
|
||||||
|
BEQ GCD_Done ; Branch to GCD_Done if R0 == R1
|
||||||
|
|
||||||
|
; If R0 > R1 (GT condition), subtract R1 from R0
|
||||||
|
BGT GT_A_B ; Branch to GT_A_B if R0 > R1
|
||||||
|
|
||||||
|
; If R0 < R1, subtract R0 from R1 (replace larger with difference)
|
||||||
|
SUB r1, r1, r0 ; R1 = R1 - R0 (R1 was larger, now smaller)
|
||||||
|
B GCD_Loop ; Branch back to GCD_Loop
|
||||||
|
|
||||||
|
; Handle case where R0 > R1
|
||||||
|
GT_A_B
|
||||||
|
SUB r0, r0, r1 ; R0 = R0 - R1 (R0 was larger, now smaller)
|
||||||
|
B GCD_Loop ; Branch back to GCD_Loop
|
||||||
|
|
||||||
|
; Step 3: GCD calculation complete
|
||||||
|
; When we reach here, R0 == R1 and contains the GCD
|
||||||
|
GCD_Done
|
||||||
|
; Load address of result storage into R2
|
||||||
|
LDR r2, =result ; R2 = address of result storage
|
||||||
|
|
||||||
|
; Store the GCD (in R0) to memory
|
||||||
|
STR r0, [r2] ; Store GCD value to [R2]
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
; Enter infinite loop to stop program execution
|
||||||
|
LoopForever
|
||||||
|
B LoopForever ; Branch to LoopForever (infinite loop)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for data section
|
||||||
|
|
||||||
|
AREA MYDATA, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Input Numbers and Result Storage
|
||||||
|
; ========================================================================================
|
||||||
|
; numA: First number for GCD calculation (48 in this example)
|
||||||
|
; numB: Second number for GCD calculation (18 in this example)
|
||||||
|
; GCD(48, 18) = 6, as calculated by the Euclidean algorithm:
|
||||||
|
; GCD(48, 18) -> GCD(18, 48-18=30) -> GCD(30, 18) -> GCD(18, 30-18=12)
|
||||||
|
; -> GCD(12, 18) -> GCD(18, 12) -> GCD(12, 18-12=6) -> GCD(6, 12)
|
||||||
|
; -> GCD(12, 6) -> GCD(6, 12-6=0) -> GCD(6, 0) = 6
|
||||||
|
numA DCD 48 ; First number for GCD
|
||||||
|
numB DCD 18 ; Second number for GCD
|
||||||
|
result DCD 0 ; Storage for the GCD result
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
102
ES/Lab/LAB4/HEXtoASCII.asm
Normal file
102
ES/Lab/LAB4/HEXtoASCII.asm
Normal file
|
@ -0,0 +1,102 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; HEXtoASCII.asm - 32-bit Hexadecimal to ASCII String Conversion
|
||||||
|
; ========================================================================================
|
||||||
|
; This program converts a 32-bit hexadecimal value into its ASCII string
|
||||||
|
; representation. Each 4-bit nibble of the hexadecimal value is converted
|
||||||
|
; to its corresponding ASCII character ('0'-'9' for digits, 'A'-'F' for
|
||||||
|
; values 10-15). The result is stored as a sequence of ASCII bytes.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Load the 32-bit hexadecimal value from memory
|
||||||
|
; 2. Initialize destination pointer for ASCII string storage
|
||||||
|
; 3. Set loop counter for 8 nibbles (32 bits = 8 nibbles)
|
||||||
|
; 4. Process each nibble from least significant to most significant:
|
||||||
|
; a. Extract lowest 4 bits using AND with 0x0F
|
||||||
|
; b. Check if digit (0-9) or letter (A-F)
|
||||||
|
; c. Convert to ASCII: add 0x30 for digits, add 0x37 for A-F
|
||||||
|
; d. Store ASCII character to destination array
|
||||||
|
; e. Shift original value right by 4 bits for next nibble
|
||||||
|
; 5. Result is an ASCII string representing the hexadecimal value
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize source and destination pointers
|
||||||
|
; R0 points to the 32-bit hexadecimal value
|
||||||
|
LDR R0, =SRC ; R0 = address of hexadecimal value
|
||||||
|
|
||||||
|
; Load the hexadecimal value into R1
|
||||||
|
LDR R1, [R0] ; R1 = 32-bit hexadecimal value (e.g., 0x12AB34CF)
|
||||||
|
|
||||||
|
; R3 points to the destination for ASCII string
|
||||||
|
LDR R3, =DST ; R3 = address of ASCII string storage
|
||||||
|
|
||||||
|
; Step 2: Initialize loop counter
|
||||||
|
; Process 8 nibbles (32 bits / 4 bits per nibble = 8 nibbles)
|
||||||
|
MOV R10, #8 ; R10 = 8 (number of nibbles to process)
|
||||||
|
|
||||||
|
; Step 3: Main conversion loop - process each nibble
|
||||||
|
UP
|
||||||
|
; Extract the lowest 4 bits (current nibble 0-15)
|
||||||
|
; AND with 0x0F isolates the least significant nibble
|
||||||
|
AND R2, R1, #0x0F ; R2 = R1 & 0x0F (extract nibble 0-15)
|
||||||
|
|
||||||
|
; Check if the nibble represents a digit (0-9) or letter (A-F)
|
||||||
|
; Compare with 9 (decimal) - values 0-9 are digits, 10-15 are A-F
|
||||||
|
CMP R2, #09 ; Compare R2 with 9
|
||||||
|
BCC DOWN ; If R2 <= 9, branch to DOWN (digit)
|
||||||
|
|
||||||
|
; Handle A-F characters (add 7 to skip punctuation in ASCII table)
|
||||||
|
; ASCII: '0'-'9' = 0x30-0x39, 'A'-'F' = 0x41-0x46
|
||||||
|
; For values 10-15: add 0x30 + 7 = 0x37 to get 'A'-'F'
|
||||||
|
ADD R2, #7 ; R2 = R2 + 7 (adjust for A-F range)
|
||||||
|
|
||||||
|
; Convert nibble to ASCII character
|
||||||
|
DOWN
|
||||||
|
; Add ASCII '0' (0x30) to convert nibble to ASCII digit/letter
|
||||||
|
; For digits 0-9: 0-9 + 0x30 = 0x30-0x39 ('0'-'9')
|
||||||
|
; For A-F: 10-15 + 0x37 = 0x41-0x46 ('A'-'F')
|
||||||
|
ADD R2, #0x30 ; R2 = R2 + 0x30 (convert to ASCII)
|
||||||
|
|
||||||
|
; Store the ASCII character to destination array
|
||||||
|
; Post-increment addressing advances R3 to next position
|
||||||
|
STR R2, [R3], #4 ; Store ASCII char and advance R3 by 4 bytes
|
||||||
|
|
||||||
|
; Shift the original value right by 4 bits to process next nibble
|
||||||
|
LSR R1, #4 ; R1 = R1 >> 4 (move to next nibble)
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
SUBS R10, #1 ; R10 = R10 - 1, set flags for branch condition
|
||||||
|
|
||||||
|
; Branch back to UP if counter is not zero
|
||||||
|
BNE UP ; If R10 != 0, continue loop
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Hexadecimal Source Value and ASCII String Storage
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC contains the 32-bit hexadecimal value: 0x12AB34CF
|
||||||
|
; This will be converted to ASCII string: "12AB34CF"
|
||||||
|
; Each nibble is converted to its ASCII equivalent:
|
||||||
|
; 0x1 -> '1', 0x2 -> '2', 0xA -> 'A', 0xB -> 'B', 0x3 -> '3', 0x4 -> '4', 0xC -> 'C', 0xF -> 'F'
|
||||||
|
SRC DCD 0x12AB34CF ; 32-bit hexadecimal value to be converted
|
||||||
|
|
||||||
|
AREA mydata, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; DST - Storage for the ASCII string result (8 characters, 32 bytes)
|
||||||
|
; Each ASCII character is stored as a word (4 bytes) for easier access
|
||||||
|
DST DCD 0 ; Space for ASCII string (will expand as needed)
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
105
ES/Lab/LAB4/HEXtoBCD.asm
Normal file
105
ES/Lab/LAB4/HEXtoBCD.asm
Normal file
|
@ -0,0 +1,105 @@
|
||||||
|
AREA RESET, DATA, READONLY
|
||||||
|
EXPORT __Vectors
|
||||||
|
__Vectors
|
||||||
|
DCD 0x10001000
|
||||||
|
DCD Reset_Handler
|
||||||
|
ALIGN
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY
|
||||||
|
ENTRY
|
||||||
|
EXPORT Reset_Handler
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Load the hexadecimal value from memory
|
||||||
|
; 2. Initialize BCD result accumulator (R4) to 0
|
||||||
|
; 3. Initialize digit position multiplier (R11) to 1 (units place)
|
||||||
|
; 4. Set loop counter for number of BCD digits to process
|
||||||
|
; 5. In each iteration:
|
||||||
|
; a. Divide current value by 10 to get quotient and remainder
|
||||||
|
; b. The remainder is the current BCD digit (0-9)
|
||||||
|
; c. Multiply digit by position value and add to BCD result
|
||||||
|
; d. Shift position multiplier left by 4 bits for next digit
|
||||||
|
; e. Use quotient as input for next iteration
|
||||||
|
; 6. Result (R4) contains the BCD representation of the original number
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize source pointer and load hexadecimal value
|
||||||
|
; R0 points to the hexadecimal value in memory
|
||||||
|
LDR R0, =SRR ; R0 = address of hexadecimal value
|
||||||
|
|
||||||
|
; Load the hexadecimal value into R1
|
||||||
|
LDR R1, [R0] ; R1 = hexadecimal value (e.g., 0x45 = 69 decimal)
|
||||||
|
|
||||||
|
; Step 2: Initialize BCD conversion variables
|
||||||
|
; R4 will accumulate the final BCD result
|
||||||
|
MOV R4, #0 ; R4 = 0 (BCD result accumulator)
|
||||||
|
|
||||||
|
; R11 holds the position multiplier for each BCD digit
|
||||||
|
; Starts at 1 for units place, shifts left by 4 bits each iteration
|
||||||
|
MOV R11, #1 ; R11 = 1 (position multiplier)
|
||||||
|
|
||||||
|
; Set loop counter for 3 BCD digits (maximum for byte values 0-255)
|
||||||
|
MOV R10, #3 ; R10 = 3 (number of BCD digits to process)
|
||||||
|
|
||||||
|
; Step 3: Main BCD conversion loop
|
||||||
|
LOOP
|
||||||
|
; Prepare divisor for decimal division
|
||||||
|
MOV R5, #10 ; R5 = 10 (decimal divisor)
|
||||||
|
|
||||||
|
; Divide current value by 10 to extract least significant digit
|
||||||
|
; UDIV performs unsigned division: R3 = R1 / 10 (quotient)
|
||||||
|
UDIV R3, R1, R5 ; R3 = R1 / 10 (quotient)
|
||||||
|
|
||||||
|
; Calculate remainder: remainder = dividend - (quotient * divisor)
|
||||||
|
; MUL computes: R6 = R3 * R5 = quotient * 10
|
||||||
|
MUL R6, R3, R5 ; R6 = R3 * 10
|
||||||
|
|
||||||
|
; Calculate remainder: R7 = R1 - R6 = R1 - (quotient * 10)
|
||||||
|
SUB R7, R1, R6 ; R7 = R1 - R6 (remainder, value 0-9)
|
||||||
|
|
||||||
|
; Multiply the BCD digit by its position value
|
||||||
|
; R8 = R7 * R11 = digit * position_multiplier
|
||||||
|
MUL R8, R7, R11 ; R8 = digit * position_value
|
||||||
|
|
||||||
|
; Add the weighted digit to the BCD result accumulator
|
||||||
|
ADD R4, R4, R8 ; R4 = R4 + R8 (accumulate BCD digit)
|
||||||
|
|
||||||
|
; Shift position multiplier left by 4 bits for next digit position
|
||||||
|
; Units (2^0) -> Tens (2^4) -> Hundreds (2^8) -> Thousands (2^12)
|
||||||
|
LSL R11, R11, #4 ; R11 = R11 << 4 (next position)
|
||||||
|
|
||||||
|
; Prepare quotient as input for next iteration
|
||||||
|
; The quotient becomes the new dividend for the next digit
|
||||||
|
MOV R1, R3 ; R1 = R3 (use quotient for next iteration)
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
SUBS R10, #1 ; R10 = R10 - 1, set flags for branch condition
|
||||||
|
|
||||||
|
; Branch back to LOOP if counter is not zero
|
||||||
|
BNE LOOP ; If R10 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
; The BCD result is stored in R4 but never saved to memory
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Hexadecimal Source Value
|
||||||
|
; ========================================================================================
|
||||||
|
; SRR contains the hexadecimal value: 0x45 (69 in decimal)
|
||||||
|
; This will be converted to BCD format. For value 69:
|
||||||
|
; 69 / 10 = 6 (quotient) with remainder 9
|
||||||
|
; 6 / 10 = 0 (quotient) with remainder 6
|
||||||
|
; Result: BCD = 0x69 (6 in tens place, 9 in units place)
|
||||||
|
; In BCD: 0110 1001 = 0x69
|
||||||
|
SRR DCD 0x45 ; Hexadecimal value to be converted to BCD
|
||||||
|
|
||||||
|
AREA mydata, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; SRC - Additional storage (seems unused in this program)
|
||||||
|
SRC DCD 0x45 ; Duplicate of SRR (possibly for testing)
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
112
ES/Lab/LAB4/HEXtoBCD2.asm
Normal file
112
ES/Lab/LAB4/HEXtoBCD2.asm
Normal file
|
@ -0,0 +1,112 @@
|
||||||
|
AREA RESET, DATA, READONLY
|
||||||
|
EXPORT __Vectors
|
||||||
|
__Vectors
|
||||||
|
DCD 0x10001000
|
||||||
|
DCD Reset_Handler
|
||||||
|
ALIGN
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY
|
||||||
|
ENTRY
|
||||||
|
EXPORT Reset_Handler
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Load the hexadecimal value from memory
|
||||||
|
; 2. Initialize BCD result accumulator (R4) to 0
|
||||||
|
; 3. Initialize digit position multiplier (R11) to 1 (units place)
|
||||||
|
; 4. Set loop counter for number of BCD digits to process
|
||||||
|
; 5. In each iteration:
|
||||||
|
; a. Perform manual division by 10 using repeated subtraction
|
||||||
|
; b. The remainder (R2) is the current BCD digit (0-9)
|
||||||
|
; c. The quotient (R3) becomes the input for the next iteration
|
||||||
|
; d. Multiply digit by position value and add to BCD result
|
||||||
|
; e. Shift position multiplier left by 4 bits for next digit
|
||||||
|
; 6. This version uses software division instead of hardware UDIV instruction
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize source pointer and load hexadecimal value
|
||||||
|
; R0 points to the hexadecimal value in memory
|
||||||
|
LDR R0, =SRR ; R0 = address of hexadecimal value
|
||||||
|
|
||||||
|
; Load the hexadecimal value into R1
|
||||||
|
LDR R1, [R0] ; R1 = hexadecimal value (e.g., 0x45 = 69 decimal)
|
||||||
|
|
||||||
|
; Step 2: Initialize BCD conversion variables
|
||||||
|
; R4 will accumulate the final BCD result
|
||||||
|
MOV R4, #0 ; R4 = 0 (BCD result accumulator)
|
||||||
|
|
||||||
|
; R11 holds the position multiplier for each BCD digit
|
||||||
|
; Starts at 1 for units place, shifts left by 4 bits each iteration
|
||||||
|
MOV R11, #1 ; R11 = 1 (position multiplier)
|
||||||
|
|
||||||
|
; Set loop counter for 3 BCD digits (maximum for byte values 0-255)
|
||||||
|
MOV R10, #3 ; R10 = 3 (number of BCD digits to process)
|
||||||
|
|
||||||
|
; Step 3: Main BCD conversion loop
|
||||||
|
LOOP
|
||||||
|
; Prepare current value for division (copy R1 to R2)
|
||||||
|
MOV R2, R1 ; R2 = R1 (dividend for this iteration)
|
||||||
|
|
||||||
|
; Initialize quotient accumulator to 0
|
||||||
|
MOV R3, #0 ; R3 = 0 (quotient accumulator)
|
||||||
|
|
||||||
|
; Step 4: Manual division by repeated subtraction
|
||||||
|
DIV_LOOP
|
||||||
|
; Compare dividend with divisor (10)
|
||||||
|
CMP R2, #10 ; Compare R2 with 10
|
||||||
|
|
||||||
|
; If dividend < 10, division is complete
|
||||||
|
BLT DIV_DONE ; Branch if R2 < 10
|
||||||
|
|
||||||
|
; Subtract 10 from dividend (equivalent to R2 = R2 - 10)
|
||||||
|
SUB R2, R2, #10 ; R2 = R2 - 10
|
||||||
|
|
||||||
|
; Increment quotient (equivalent to quotient = quotient + 1)
|
||||||
|
ADD R3, R3, #1 ; R3 = R3 + 1
|
||||||
|
|
||||||
|
; Continue division loop
|
||||||
|
B DIV_LOOP ; Branch back to DIV_LOOP
|
||||||
|
|
||||||
|
; Step 5: Division complete - R2 = remainder (0-9), R3 = quotient
|
||||||
|
DIV_DONE
|
||||||
|
; Multiply the BCD digit (remainder) by its position value
|
||||||
|
; R8 = R2 * R11 = digit * position_multiplier
|
||||||
|
MUL R8, R2, R11 ; R8 = digit * position_value
|
||||||
|
|
||||||
|
; Add the weighted digit to the BCD result accumulator
|
||||||
|
ADD R4, R4, R8 ; R4 = R4 + R8 (accumulate BCD digit)
|
||||||
|
|
||||||
|
; Shift position multiplier left by 4 bits for next digit position
|
||||||
|
; Units (2^0) -> Tens (2^4) -> Hundreds (2^8) -> Thousands (2^12)
|
||||||
|
LSL R11, R11, #4 ; R11 = R11 << 4 (next position)
|
||||||
|
|
||||||
|
; Prepare quotient as input for next iteration
|
||||||
|
; The quotient becomes the new dividend for the next digit
|
||||||
|
MOV R1, R3 ; R1 = R3 (use quotient for next iteration)
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
SUBS R10, R10, #1 ; R10 = R10 - 1, set flags for branch condition
|
||||||
|
|
||||||
|
; Branch back to LOOP if counter is not zero
|
||||||
|
BNE LOOP ; If R10 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 6: Program termination
|
||||||
|
; The BCD result is stored in R4 but never saved to memory
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Hexadecimal Source Value
|
||||||
|
; ========================================================================================
|
||||||
|
; SRR contains the hexadecimal value: 0x45 (69 in decimal)
|
||||||
|
; This will be converted to BCD format using manual division by repeated subtraction.
|
||||||
|
; For value 69:
|
||||||
|
; First iteration: 69 / 10 = 6 (quotient) with remainder 9
|
||||||
|
; Second iteration: 6 / 10 = 0 (quotient) with remainder 6
|
||||||
|
; Result: BCD = 0x69 (6 in tens place, 9 in units place)
|
||||||
|
; In BCD: 0110 1001 = 0x69
|
||||||
|
SRR DCD 0x45 ; Hexadecimal value to be converted to BCD
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
112
ES/Lab/LAB5/FACTORIAL.asm
Normal file
112
ES/Lab/LAB5/FACTORIAL.asm
Normal file
|
@ -0,0 +1,112 @@
|
||||||
|
AREA RESET, DATA, READONLY
|
||||||
|
EXPORT __Vectors
|
||||||
|
__Vectors
|
||||||
|
DCD 0x10001000
|
||||||
|
DCD Reset_Handler
|
||||||
|
ALIGN
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY
|
||||||
|
ENTRY
|
||||||
|
EXPORT Reset_Handler
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; FACTORIAL.asm - Recursive Factorial Calculation
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates recursive factorial computation using ARM assembly.
|
||||||
|
; The factorial of a number n (n!) is the product of all positive integers less
|
||||||
|
; than or equal to n. This implementation uses the call stack to handle recursion.
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Load the input number (5) into R1
|
||||||
|
; 2. Call the recursive factorial function (fact)
|
||||||
|
; 3. Store the result from R0 to memory location 0x10001000
|
||||||
|
; 4. Enter infinite loop for program termination
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Load input parameter and call factorial function
|
||||||
|
; Load the number for which to calculate factorial (n = 5)
|
||||||
|
LDR R1, =5 ; R1 = 5 (input parameter for factorial)
|
||||||
|
|
||||||
|
; Call the recursive factorial function
|
||||||
|
; BL (Branch with Link) saves return address in LR and jumps to fact
|
||||||
|
BL fact ; Call factorial function, result returned in R0
|
||||||
|
|
||||||
|
; Step 2: Store the result
|
||||||
|
; Load destination address into R12
|
||||||
|
LDR R12, =0x10001000 ; R12 = 0x10001000 (result storage address)
|
||||||
|
|
||||||
|
; Store the factorial result (in R0) to memory
|
||||||
|
STR R0, [R12] ; Store factorial result to [R12]
|
||||||
|
|
||||||
|
; Step 3: Program termination
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; fact - Recursive Factorial Function
|
||||||
|
; ========================================================================================
|
||||||
|
; Recursive algorithm for calculating n!
|
||||||
|
; Base case: if n <= 1, return 1
|
||||||
|
; Recursive case: return n * factorial(n-1)
|
||||||
|
; Parameters: R1 = n (input)
|
||||||
|
; Returns: R0 = n! (result)
|
||||||
|
; Uses: R2 (temporary register for stack operations)
|
||||||
|
|
||||||
|
fact
|
||||||
|
; Step 1: Check base case
|
||||||
|
; Compare input parameter with 1
|
||||||
|
CMP R1, #1 ; Compare R1 with 1
|
||||||
|
|
||||||
|
; If R1 <= 1, branch to base_case
|
||||||
|
BLE base_case ; If R1 <= 1, return 1
|
||||||
|
|
||||||
|
; Step 2: Recursive case - prepare for recursive call
|
||||||
|
; Save current R1 and LR (return address) on the stack
|
||||||
|
PUSH{R1, LR} ; Push R1 and LR onto stack
|
||||||
|
|
||||||
|
; Decrement n for recursive call: R1 = R1 - 1
|
||||||
|
SUB R1, R1, #1 ; R1 = R1 - 1
|
||||||
|
|
||||||
|
; Recursive call to factorial function
|
||||||
|
BL fact ; Call fact(R1-1), result in R0
|
||||||
|
|
||||||
|
; Step 3: Return from recursion - multiply result
|
||||||
|
; Restore saved R1 (original n) and LR from stack
|
||||||
|
POP{R2, LR} ; Pop LR and original R1 into R2
|
||||||
|
|
||||||
|
; Multiply current result (R0) by original n (R2)
|
||||||
|
; R0 = R0 * R2 = factorial(n-1) * n
|
||||||
|
MUL R0, R0, R2 ; R0 = R0 * R2
|
||||||
|
|
||||||
|
; Return from function (branch to address in LR)
|
||||||
|
BX LR ; Return to caller
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; base_case - Base case handler for factorial
|
||||||
|
; ========================================================================================
|
||||||
|
; When n <= 1, factorial = 1
|
||||||
|
; Returns: R0 = 1
|
||||||
|
|
||||||
|
base_case
|
||||||
|
; Set return value to 1 (base case for factorial)
|
||||||
|
MOV R0, #1 ; R0 = 1 (factorial of 0 or 1 is 1)
|
||||||
|
|
||||||
|
; Return from function
|
||||||
|
BX LR ; Return to caller
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Execution Example:
|
||||||
|
; ========================================================================================
|
||||||
|
; Calculating factorial(5):
|
||||||
|
; fact(5) -> calls fact(4) -> calls fact(3) -> calls fact(2) -> calls fact(1)
|
||||||
|
; fact(1) returns 1
|
||||||
|
; fact(2) returns 2 * 1 = 2
|
||||||
|
; fact(3) returns 3 * 2 = 6
|
||||||
|
; fact(4) returns 4 * 6 = 24
|
||||||
|
; fact(5) returns 5 * 24 = 120
|
||||||
|
; Final result: 120 is stored at memory location 0x10001000
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
50
ES/Lab/LAB5/INSERTION.asm
Normal file
50
ES/Lab/LAB5/INSERTION.asm
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
AREA RESET, DATA, READONLY
|
||||||
|
EXPORT __Vectors
|
||||||
|
__Vectors
|
||||||
|
DCD 0x10001000
|
||||||
|
DCD Reset_Handler
|
||||||
|
ALIGN
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY
|
||||||
|
ENTRY
|
||||||
|
EXPORT Reset_Handler
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
LDR R0, =ARRAY
|
||||||
|
MOV R9, #9
|
||||||
|
LDR R9, [R9]
|
||||||
|
ADD R9, R0, R9, LSL #2 ; address of one element from the end
|
||||||
|
ADD R1, R0, #4 ; i pointer
|
||||||
|
|
||||||
|
OUTER
|
||||||
|
CMP R1, R9 ; checks append if counter
|
||||||
|
BGE DONE
|
||||||
|
|
||||||
|
LDR R5, [R1]
|
||||||
|
MOV R2, R1 ; j pointer (inner loop)
|
||||||
|
|
||||||
|
INNER
|
||||||
|
SUB R2, R2, #4 ; decrements j to previous element
|
||||||
|
CMP R2, R0
|
||||||
|
BLT INSERT
|
||||||
|
|
||||||
|
LDR R8, [R2]
|
||||||
|
CMP R8, R5
|
||||||
|
BLE INSERT
|
||||||
|
|
||||||
|
STR R8, [R2, #4]
|
||||||
|
ADD R1, R1, #4
|
||||||
|
B INNER
|
||||||
|
|
||||||
|
INSERT
|
||||||
|
STR R5, [R2, #4]
|
||||||
|
ADD R1, R1, #4
|
||||||
|
B OUTER
|
||||||
|
|
||||||
|
DONE
|
||||||
|
B DONE
|
||||||
|
|
||||||
|
AREA mydata, DATA, READWRITE
|
||||||
|
ARRAY DCD 5,2,8,1,9,4,6,3,7
|
||||||
|
|
||||||
|
END
|
3
ES/Lab/LAB5/Questions.md
Normal file
3
ES/Lab/LAB5/Questions.md
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
1. Sort using insertion sort
|
||||||
|
2. [Factorial using recursion](https://git.aadit.cc/aadit/MIT-Curricular/src/branch/main/ES/Lab/LAB5/FACTORIAL.asm)
|
||||||
|
3. Search for an element and store the address
|
45
ES/Lab/LAB5/SEARCH.asm
Normal file
45
ES/Lab/LAB5/SEARCH.asm
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
AREA RESET, DATA, READONLY
|
||||||
|
EXPORT __Vectors
|
||||||
|
__Vectors
|
||||||
|
DCD 0x10001000
|
||||||
|
DCD Reset_Handler
|
||||||
|
ALIGN
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY
|
||||||
|
ENTRY
|
||||||
|
EXPORT Reset_Handler
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
MOV R5, #8
|
||||||
|
LDR R0, =SRC
|
||||||
|
LDR R2, =target
|
||||||
|
LDR R7, [R2]
|
||||||
|
LDR R3, =result
|
||||||
|
LDR R8, =found_addr
|
||||||
|
MOV R4, #0
|
||||||
|
STR R4, [R3]
|
||||||
|
STR R4, [R8]
|
||||||
|
loop
|
||||||
|
LDR R1, [R0], #4
|
||||||
|
CMP R1, R7
|
||||||
|
BEQ found
|
||||||
|
SUBS R5, R5, #1
|
||||||
|
BNE loop
|
||||||
|
B STOP
|
||||||
|
found
|
||||||
|
MOV R4, #1
|
||||||
|
STR R4, [R3]
|
||||||
|
SUB R6, R0, #4
|
||||||
|
STR R6, [R8]
|
||||||
|
STOP
|
||||||
|
B STOP
|
||||||
|
|
||||||
|
AREA CONSTS, DATA, READONLY
|
||||||
|
SRC DCD 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x1, 0x2
|
||||||
|
target DCD 0x1
|
||||||
|
|
||||||
|
AREA DATA1, DATA, READWRITE
|
||||||
|
result DCD 0
|
||||||
|
found_addr DCD 0
|
||||||
|
|
||||||
|
END
|
16
ES/Lab/LAB6/BULBARR.c
Normal file
16
ES/Lab/LAB6/BULBARR.c
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
int i;
|
||||||
|
// from P1.24 -> 31
|
||||||
|
LPC_PINCON->PINSEL3 &= 0x0000FFFF;
|
||||||
|
|
||||||
|
LPC_GPIO1->FIODIR = 0xFF000000;
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
LPC_GPIO1-> FIOSET=0xFF000000;
|
||||||
|
for(i=0; i<1000; i++);
|
||||||
|
LPC_GPIO1->FIOCLR=0xFF000000;
|
||||||
|
for(i=0; i<1000; i++);
|
||||||
|
}
|
||||||
|
}
|
24
ES/Lab/LAB6/BinaryUpCounter.c
Normal file
24
ES/Lab/LAB6/BinaryUpCounter.c
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
int i;
|
||||||
|
unsigned long x, j;
|
||||||
|
LPC_PINCON->PINSEL0 = 0;
|
||||||
|
|
||||||
|
LPC_GPIO0->FIODIR = 0xFF<<15;
|
||||||
|
|
||||||
|
x = 1<<15; // new variable
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
x = 1<<15;
|
||||||
|
for(i=0;i<256;i++){
|
||||||
|
LPC_GPIO0->FIOSET=x;
|
||||||
|
for(j=0; j<2000000; j++);
|
||||||
|
|
||||||
|
x = x + (1<<15);
|
||||||
|
|
||||||
|
LPC_GPIO0->FIOCLR=-x;
|
||||||
|
for(j=0; j<2000000; j++);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
31
ES/Lab/LAB6/JOHNSON_Counter.c
Normal file
31
ES/Lab/LAB6/JOHNSON_Counter.c
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
unsigned long x, i, j;
|
||||||
|
// from P1.24 -> 31
|
||||||
|
LPC_PINCON->PINSEL0 = 0; // values
|
||||||
|
|
||||||
|
LPC_GPIO0->FIODIR = 0xFF<<15;
|
||||||
|
|
||||||
|
x = 1<<15; // new variable
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
x = 1<<15;
|
||||||
|
|
||||||
|
// LOOP to fill 24->31 incrementally
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOSET=x;
|
||||||
|
x = x<<1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
// delay
|
||||||
|
|
||||||
|
// LOOP to empty 24->31 incrementally.
|
||||||
|
x = 1<<15;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOCLR=x;
|
||||||
|
x = x<<1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
19
ES/Lab/LAB6/init.c
Normal file
19
ES/Lab/LAB6/init.c
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
// Embedded C Programming
|
||||||
|
// 5 Ports
|
||||||
|
// Each Port has 32 pins (PX0.31)
|
||||||
|
// Each Port has 2 PINSEL (0-15, 16-31)
|
||||||
|
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
int i; // variable declarations have to be global
|
||||||
|
LPC_PINCON->PINSEL0 &= 0xFF0000FF;
|
||||||
|
LPC_GPIO0->FIODIR = 0x00000FF0;
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
LPC_GPIO0-> FIOSET=0x00000FF0;
|
||||||
|
for(i=0; i<1000; i++); //delay
|
||||||
|
LPC_GPIO0->FIOCLR=0x00000FF0;
|
||||||
|
for(i=0; i<1000; i++); //delay
|
||||||
|
}
|
||||||
|
}
|
17
ES/Lab/LAB6/valuelist.c
Normal file
17
ES/Lab/LAB6/valuelist.c
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
int i;
|
||||||
|
// from P2.15 -> P2.22
|
||||||
|
LPC_PINCON->PINSEL4 &= 0x3FFFFFFF; // all values except P2.15 are taken as 1
|
||||||
|
LPC_PINCON->PINSEL5 &= 0xFFFFC000; // all values except P2.16 (0,1) -> P2.22 (12,13) are taken as 1
|
||||||
|
|
||||||
|
LPC_GPIO2->FIODIR = 0x007F8000; // all values except 15 -> 22 are taken as 0 (and GPIO2 because it's PIN 2)
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
LPC_GPIO2-> FIOSET=0x007F8000;
|
||||||
|
for(i=0; i<1000; i++);
|
||||||
|
LPC_GPIO2->FIOCLR=0x007F8000;
|
||||||
|
for(i=0; i<1000; i++);
|
||||||
|
}
|
||||||
|
}
|
53
ES/Lab/Lab1/Init/DATATRANSFER.asm
Normal file
53
ES/Lab/Lab1/Init/DATATRANSFER.asm
Normal file
|
@ -0,0 +1,53 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; DATATRANSFER.asm - Basic Data Transfer Operations Demonstration
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates various ways to transfer immediate data into ARM registers
|
||||||
|
; using different number formats (decimal, hexadecimal, binary, and negative values).
|
||||||
|
; The program loads different types of immediate values into registers R0-R5 to show
|
||||||
|
; the flexibility of ARM's MOV instruction for data transfer operations.
|
||||||
|
|
||||||
|
AREA RESET,DATA,READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA mycode, CODE, READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
Reset_Handler ; Main program starts here
|
||||||
|
; Step 1: Load decimal immediate value
|
||||||
|
; MOV instruction transfers immediate data (value 10) into register R0
|
||||||
|
; This demonstrates basic decimal number loading
|
||||||
|
MOV R0,#10 ; R0 = 10 (decimal)
|
||||||
|
|
||||||
|
; Step 2: Load hexadecimal immediate value
|
||||||
|
; Load hexadecimal value 0x10 (16 decimal) into register R1
|
||||||
|
; Shows how hexadecimal values are represented in assembly
|
||||||
|
MOV R1, #0x10 ; R1 = 0x10 (16 decimal)
|
||||||
|
|
||||||
|
; Step 3: Load binary immediate value
|
||||||
|
; Load binary value 1010 (which equals 10 decimal) into register R3
|
||||||
|
; The '2_' prefix indicates binary notation in ARM assembly
|
||||||
|
MOV R3, #2_1010 ; R3 = 2_1010 (10 decimal in binary)
|
||||||
|
|
||||||
|
; Step 4: Load another decimal immediate value
|
||||||
|
; Load decimal value 34 into register R4
|
||||||
|
; The '5_' prefix indicates decimal notation (though redundant here)
|
||||||
|
MOV R4, #5_34 ; R4 = 34 (decimal)
|
||||||
|
|
||||||
|
; Step 5: Load negative immediate value
|
||||||
|
; Load negative value -8 into register R5
|
||||||
|
; Demonstrates how negative numbers are handled in immediate loads
|
||||||
|
MOV R5, #-8 ; R5 = -8 (negative value)
|
||||||
|
|
||||||
|
; Step 6: Program termination
|
||||||
|
; Create an infinite loop to stop program execution
|
||||||
|
; This prevents the processor from executing undefined instructions
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
1
ES/Lab/Lab1/Init/DATATRANSFER.d
Normal file
1
ES/Lab/Lab1/Init/DATATRANSFER.d
Normal file
|
@ -0,0 +1 @@
|
||||||
|
DATATRANSFER.o: DATATRANSFER.asm
|
86
ES/Lab/Lab1/Init/DATATRANSFER.lst
Normal file
86
ES/Lab/Lab1/Init/DATATRANSFER.lst
Normal file
|
@ -0,0 +1,86 @@
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
ARM Macro Assembler Page 1
|
||||||
|
|
||||||
|
|
||||||
|
1 00000000 AREA RESET,DATA,READONLY
|
||||||
|
2 00000000 EXPORT __Vectors
|
||||||
|
3 00000000 __Vectors
|
||||||
|
4 00000000 10001000 DCD 0x10001000 ;
|
||||||
|
5 00000004 00000000 DCD Reset_Handler ;
|
||||||
|
6 00000008 ALIGN
|
||||||
|
7 00000008 AREA mycode, CODE, READONLY
|
||||||
|
8 00000000 ENTRY
|
||||||
|
9 00000000 EXPORT Reset_Handler
|
||||||
|
10 00000000 Reset_Handler
|
||||||
|
11 00000000 F04F 000A MOV R0,#10
|
||||||
|
12 00000004 F04F 0110 MOV R1, #0x10
|
||||||
|
13 00000008 F04F 030A MOV R3, #2_1010
|
||||||
|
14 0000000C F04F 0413 MOV R4, #5_34
|
||||||
|
15 00000010 F06F 0507 MOV R5, #-8
|
||||||
|
16 00000014
|
||||||
|
17 00000014 STOP
|
||||||
|
18 00000014 E7FE B STOP
|
||||||
|
19 00000016
|
||||||
|
20 00000016 END ;
|
||||||
|
Command Line: --debug --xref --cpu=Cortex-M3 --apcs=interwork --depend=DATATRAN
|
||||||
|
SFER.d -oDATATRANSFER.o -IC:\Keil\ARM\RV31\INC -IC:\Keil\ARM\CMSIS\Include -IC:
|
||||||
|
\Keil\ARM\Inc\NXP\LPC17xx --predefine="__EVAL SETA 1" --list=DATATRANSFER.lst D
|
||||||
|
ATATRANSFER.asm
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
ARM Macro Assembler Page 1 Alphabetic symbol ordering
|
||||||
|
Relocatable symbols
|
||||||
|
|
||||||
|
RESET 00000000
|
||||||
|
|
||||||
|
Symbol: RESET
|
||||||
|
Definitions
|
||||||
|
At line 1 in file DATATRANSFER.asm
|
||||||
|
Uses
|
||||||
|
None
|
||||||
|
Comment: RESET unused
|
||||||
|
__Vectors 00000000
|
||||||
|
|
||||||
|
Symbol: __Vectors
|
||||||
|
Definitions
|
||||||
|
At line 3 in file DATATRANSFER.asm
|
||||||
|
Uses
|
||||||
|
At line 2 in file DATATRANSFER.asm
|
||||||
|
Comment: __Vectors used once
|
||||||
|
2 symbols
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
ARM Macro Assembler Page 1 Alphabetic symbol ordering
|
||||||
|
Relocatable symbols
|
||||||
|
|
||||||
|
Reset_Handler 00000000
|
||||||
|
|
||||||
|
Symbol: Reset_Handler
|
||||||
|
Definitions
|
||||||
|
At line 10 in file DATATRANSFER.asm
|
||||||
|
Uses
|
||||||
|
At line 5 in file DATATRANSFER.asm
|
||||||
|
At line 9 in file DATATRANSFER.asm
|
||||||
|
|
||||||
|
STOP 00000014
|
||||||
|
|
||||||
|
Symbol: STOP
|
||||||
|
Definitions
|
||||||
|
At line 17 in file DATATRANSFER.asm
|
||||||
|
Uses
|
||||||
|
At line 18 in file DATATRANSFER.asm
|
||||||
|
Comment: STOP used once
|
||||||
|
mycode 00000000
|
||||||
|
|
||||||
|
Symbol: mycode
|
||||||
|
Definitions
|
||||||
|
At line 7 in file DATATRANSFER.asm
|
||||||
|
Uses
|
||||||
|
None
|
||||||
|
Comment: mycode unused
|
||||||
|
3 symbols
|
||||||
|
336 symbols in table
|
BIN
ES/Lab/Lab1/Init/DATATRANSFER.o
Normal file
BIN
ES/Lab/Lab1/Init/DATATRANSFER.o
Normal file
Binary file not shown.
1
ES/Lab/Lab1/Init/description.md
Normal file
1
ES/Lab/Lab1/Init/description.md
Normal file
|
@ -0,0 +1 @@
|
||||||
|
Taught MOV, DCD etc.
|
BIN
ES/Lab/Lab1/Init/init.axf
Normal file
BIN
ES/Lab/Lab1/Init/init.axf
Normal file
Binary file not shown.
35
ES/Lab/Lab1/Init/init.htm
Normal file
35
ES/Lab/Lab1/Init/init.htm
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||||
|
<html><head>
|
||||||
|
<title>Static Call Graph - [F:\230953344\ES\Lab1\init\init.axf]</title></head>
|
||||||
|
<body><HR>
|
||||||
|
<H1>Static Call Graph for image F:\230953344\ES\Lab1\init\init.axf</H1><HR>
|
||||||
|
<BR><P>#<CALLGRAPH># ARM Linker, 5.03 [Build 24]: Last Updated: Thu Jul 24 12:55:03 2025
|
||||||
|
<BR><P>
|
||||||
|
<H3>Maximum Stack Usage = 0 bytes + Unknown(Functions without stacksize, Untraceable Function Pointers)</H3><H3>
|
||||||
|
Call chain for Maximum Stack Depth:</H3>
|
||||||
|
|
||||||
|
<P>
|
||||||
|
<H3>
|
||||||
|
Functions with no stack information
|
||||||
|
</H3><UL>
|
||||||
|
<LI><a href="#[1]">Reset_Handler</a>
|
||||||
|
</UL>
|
||||||
|
</UL>
|
||||||
|
<P>
|
||||||
|
<H3>
|
||||||
|
Function Pointers
|
||||||
|
</H3><UL>
|
||||||
|
<LI><a href="#[1]">Reset_Handler</a> from datatransfer.o(mycode) referenced from datatransfer.o(RESET)
|
||||||
|
</UL>
|
||||||
|
<P>
|
||||||
|
<H3>
|
||||||
|
Global Symbols
|
||||||
|
</H3>
|
||||||
|
<P><STRONG><a name="[1]"></a>Reset_Handler</STRONG> (Thumb, 0 bytes, Stack size unknown bytes, datatransfer.o(mycode))
|
||||||
|
<P>
|
||||||
|
<H3>
|
||||||
|
Local Symbols
|
||||||
|
</H3><P>
|
||||||
|
<H3>
|
||||||
|
Undefined Global Symbols
|
||||||
|
</H3><HR></body></html>
|
4
ES/Lab/Lab1/Init/init.lnp
Normal file
4
ES/Lab/Lab1/Init/init.lnp
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
--cpu Cortex-M3 "datatransfer.o"
|
||||||
|
--ro-base 0x00000000 --entry 0x00000000 --rw-base 0x10000000 --entry Reset_Handler --first __Vectors --strict --summary_stderr --info summarysizes --map --xref --callgraph --symbols
|
||||||
|
--info sizes --info totals --info unused --info veneers
|
||||||
|
--list ".\init.map" -o init.axf
|
94
ES/Lab/Lab1/Init/init.map
Normal file
94
ES/Lab/Lab1/Init/init.map
Normal file
|
@ -0,0 +1,94 @@
|
||||||
|
ARM Linker, 5.03 [Build 24] [MDK-ARM Lite]
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
Section Cross References
|
||||||
|
|
||||||
|
datatransfer.o(RESET) refers to datatransfer.o(mycode) for Reset_Handler
|
||||||
|
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
Image Symbol Table
|
||||||
|
|
||||||
|
Local Symbols
|
||||||
|
|
||||||
|
Symbol Name Value Ov Type Size Object(Section)
|
||||||
|
|
||||||
|
RESET 0x00000000 Section 8 datatransfer.o(RESET)
|
||||||
|
DATATRANSFER.asm 0x00000000 Number 0 datatransfer.o ABSOLUTE
|
||||||
|
mycode 0x00000008 Section 22 datatransfer.o(mycode)
|
||||||
|
|
||||||
|
Global Symbols
|
||||||
|
|
||||||
|
Symbol Name Value Ov Type Size Object(Section)
|
||||||
|
|
||||||
|
BuildAttributes$$THM_ISAv4$P$D$K$B$S$PE$A:L22UL41UL21$X:L11$S22US41US21$IEEE1$IW$USESV6$~STKCKD$USESV7$~SHL$OSPACE$EBA8$STANDARDLIB$PRES8$EABIv2 0x00000000 Number 0 anon$$obj.o ABSOLUTE
|
||||||
|
__Vectors 0x00000000 Data 0 datatransfer.o(RESET)
|
||||||
|
Reset_Handler 0x00000009 Thumb Code 0 datatransfer.o(mycode)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
Memory Map of the image
|
||||||
|
|
||||||
|
Image Entry point : 0x00000009
|
||||||
|
|
||||||
|
Load Region LR_1 (Base: 0x00000000, Size: 0x00000020, Max: 0xffffffff, ABSOLUTE)
|
||||||
|
|
||||||
|
Execution Region ER_RO (Base: 0x00000000, Size: 0x00000020, Max: 0xffffffff, ABSOLUTE)
|
||||||
|
|
||||||
|
Base Addr Size Type Attr Idx E Section Name Object
|
||||||
|
|
||||||
|
0x00000000 0x00000008 Data RO 1 RESET datatransfer.o
|
||||||
|
0x00000008 0x00000016 Code RO 2 * mycode datatransfer.o
|
||||||
|
|
||||||
|
|
||||||
|
Execution Region ER_RW (Base: 0x10000000, Size: 0x00000000, Max: 0xffffffff, ABSOLUTE)
|
||||||
|
|
||||||
|
**** No section assigned to this execution region ****
|
||||||
|
|
||||||
|
|
||||||
|
Execution Region ER_ZI (Base: 0x10000000, Size: 0x00000000, Max: 0xffffffff, ABSOLUTE)
|
||||||
|
|
||||||
|
**** No section assigned to this execution region ****
|
||||||
|
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
Image component sizes
|
||||||
|
|
||||||
|
|
||||||
|
Code (inc. data) RO Data RW Data ZI Data Debug Object Name
|
||||||
|
|
||||||
|
22 0 8 0 0 204 datatransfer.o
|
||||||
|
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
24 0 8 0 0 204 Object Totals
|
||||||
|
0 0 0 0 0 0 (incl. Generated)
|
||||||
|
2 0 0 0 0 0 (incl. Padding)
|
||||||
|
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
0 0 0 0 0 0 Library Totals
|
||||||
|
0 0 0 0 0 0 (incl. Padding)
|
||||||
|
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
Code (inc. data) RO Data RW Data ZI Data Debug
|
||||||
|
|
||||||
|
24 0 8 0 0 204 Grand Totals
|
||||||
|
24 0 8 0 0 204 ELF Image Totals
|
||||||
|
24 0 8 0 0 0 ROM Totals
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
Total RO Size (Code + RO Data) 32 ( 0.03kB)
|
||||||
|
Total RW Size (RW Data + ZI Data) 0 ( 0.00kB)
|
||||||
|
Total ROM Size (Code + RO Data + RW Data) 32 ( 0.03kB)
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
|
19
ES/Lab/Lab1/Init/init.tra
Normal file
19
ES/Lab/Lab1/Init/init.tra
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
*** Creating Trace Output File 'init.tra' Ok.
|
||||||
|
### Preparing for ADS-LD.
|
||||||
|
### Creating ADS-LD Command Line
|
||||||
|
### List of Objects: adding '"datatransfer.o"'
|
||||||
|
### ADS-LD Command completed:
|
||||||
|
--cpu Cortex-M3 "datatransfer.o"
|
||||||
|
--ro-base 0x00000000 --entry 0x00000000 --rw-base 0x10000000 --entry Reset_Handler --first __Vectors --strict --summary_stderr --info summarysizes --map --xref --callgraph --symbols
|
||||||
|
--info sizes --info totals --info unused --info veneers
|
||||||
|
--list ".\init.map" -o init.axf### Preparing Environment (PrepEnvAds)
|
||||||
|
### ADS-LD Output File: 'init.axf'
|
||||||
|
### ADS-LD Command File: 'init.lnp'
|
||||||
|
### Checking for dirty Components...
|
||||||
|
### Creating CmdFile 'init.lnp', Handle=0x00000D34
|
||||||
|
### Writing '.lnp' file
|
||||||
|
### ADS-LD Command file 'init.lnp' is ready.
|
||||||
|
### ADS-LD: About to start ADS-LD Thread.
|
||||||
|
### ADS-LD: executed with 0 errors
|
||||||
|
### Updating obj list
|
||||||
|
### LDADS_file() completed.
|
2648
ES/Lab/Lab1/Init/init.uvgui.STUDENT
Normal file
2648
ES/Lab/Lab1/Init/init.uvgui.STUDENT
Normal file
File diff suppressed because one or more lines are too long
2648
ES/Lab/Lab1/Init/init.uvgui_STUDENT.bak
Normal file
2648
ES/Lab/Lab1/Init/init.uvgui_STUDENT.bak
Normal file
File diff suppressed because one or more lines are too long
232
ES/Lab/Lab1/Init/init.uvopt
Normal file
232
ES/Lab/Lab1/Init/init.uvopt
Normal file
|
@ -0,0 +1,232 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
|
||||||
|
<ProjectOpt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="project_opt.xsd">
|
||||||
|
|
||||||
|
<SchemaVersion>1.0</SchemaVersion>
|
||||||
|
|
||||||
|
<Header>### uVision Project, (C) Keil Software</Header>
|
||||||
|
|
||||||
|
<Extensions>
|
||||||
|
<cExt>*.c</cExt>
|
||||||
|
<aExt>*.s*; *.src; *.a*</aExt>
|
||||||
|
<oExt>*.obj</oExt>
|
||||||
|
<lExt>*.lib</lExt>
|
||||||
|
<tExt>*.txt; *.h; *.inc</tExt>
|
||||||
|
<pExt>*.plm</pExt>
|
||||||
|
<CppX>*.cpp</CppX>
|
||||||
|
</Extensions>
|
||||||
|
|
||||||
|
<DaveTm>
|
||||||
|
<dwLowDateTime>0</dwLowDateTime>
|
||||||
|
<dwHighDateTime>0</dwHighDateTime>
|
||||||
|
</DaveTm>
|
||||||
|
|
||||||
|
<Target>
|
||||||
|
<TargetName>Target 1</TargetName>
|
||||||
|
<ToolsetNumber>0x4</ToolsetNumber>
|
||||||
|
<ToolsetName>ARM-ADS</ToolsetName>
|
||||||
|
<TargetOption>
|
||||||
|
<CLKADS>12000000</CLKADS>
|
||||||
|
<OPTTT>
|
||||||
|
<gFlags>0</gFlags>
|
||||||
|
<BeepAtEnd>1</BeepAtEnd>
|
||||||
|
<RunSim>1</RunSim>
|
||||||
|
<RunTarget>0</RunTarget>
|
||||||
|
</OPTTT>
|
||||||
|
<OPTHX>
|
||||||
|
<HexSelection>1</HexSelection>
|
||||||
|
<FlashByte>65535</FlashByte>
|
||||||
|
<HexRangeLowAddress>0</HexRangeLowAddress>
|
||||||
|
<HexRangeHighAddress>0</HexRangeHighAddress>
|
||||||
|
<HexOffset>0</HexOffset>
|
||||||
|
</OPTHX>
|
||||||
|
<OPTLEX>
|
||||||
|
<PageWidth>79</PageWidth>
|
||||||
|
<PageLength>66</PageLength>
|
||||||
|
<TabStop>8</TabStop>
|
||||||
|
<ListingPath>.\</ListingPath>
|
||||||
|
</OPTLEX>
|
||||||
|
<ListingPage>
|
||||||
|
<CreateCListing>1</CreateCListing>
|
||||||
|
<CreateAListing>1</CreateAListing>
|
||||||
|
<CreateLListing>1</CreateLListing>
|
||||||
|
<CreateIListing>0</CreateIListing>
|
||||||
|
<AsmCond>1</AsmCond>
|
||||||
|
<AsmSymb>1</AsmSymb>
|
||||||
|
<AsmXref>0</AsmXref>
|
||||||
|
<CCond>1</CCond>
|
||||||
|
<CCode>0</CCode>
|
||||||
|
<CListInc>0</CListInc>
|
||||||
|
<CSymb>0</CSymb>
|
||||||
|
<LinkerCodeListing>0</LinkerCodeListing>
|
||||||
|
</ListingPage>
|
||||||
|
<OPTXL>
|
||||||
|
<LMap>1</LMap>
|
||||||
|
<LComments>1</LComments>
|
||||||
|
<LGenerateSymbols>1</LGenerateSymbols>
|
||||||
|
<LLibSym>1</LLibSym>
|
||||||
|
<LLines>1</LLines>
|
||||||
|
<LLocSym>1</LLocSym>
|
||||||
|
<LPubSym>1</LPubSym>
|
||||||
|
<LXref>0</LXref>
|
||||||
|
<LExpSel>0</LExpSel>
|
||||||
|
</OPTXL>
|
||||||
|
<OPTFL>
|
||||||
|
<tvExp>1</tvExp>
|
||||||
|
<tvExpOptDlg>0</tvExpOptDlg>
|
||||||
|
<IsCurrentTarget>1</IsCurrentTarget>
|
||||||
|
</OPTFL>
|
||||||
|
<CpuCode>8</CpuCode>
|
||||||
|
<Books>
|
||||||
|
<Book>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Title>Data Sheet</Title>
|
||||||
|
<Path>DATASHTS\PHILIPS\LPC176x_DS.pdf</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>1</Number>
|
||||||
|
<Title>User Manual</Title>
|
||||||
|
<Path>DATASHTS\PHILIPS\LPC17xx_UM.pdf</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>2</Number>
|
||||||
|
<Title>Errata Sheet</Title>
|
||||||
|
<Path>DATASHTS\PHILIPS\LPC1768_ES.pdf</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>3</Number>
|
||||||
|
<Title>Technical Reference Manual</Title>
|
||||||
|
<Path>datashts\arm\cortex_m3\r2p1\DDI0337I_CORTEXM3_R2P1_TRM.PDF</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>4</Number>
|
||||||
|
<Title>Generic User Guide</Title>
|
||||||
|
<Path>datashts\arm\cortex_m3\r2p1\DUI0552A_CORTEX_M3_DGUG.PDF</Path>
|
||||||
|
</Book>
|
||||||
|
</Books>
|
||||||
|
<DllOpt>
|
||||||
|
<SimDllName>SARMCM3.DLL</SimDllName>
|
||||||
|
<SimDllArguments>-MPU</SimDllArguments>
|
||||||
|
<SimDlgDllName>DARMP1.DLL</SimDlgDllName>
|
||||||
|
<SimDlgDllArguments>-pLPC1768</SimDlgDllArguments>
|
||||||
|
<TargetDllName>SARMCM3.DLL</TargetDllName>
|
||||||
|
<TargetDllArguments>-MPU</TargetDllArguments>
|
||||||
|
<TargetDlgDllName>TARMP1.DLL</TargetDlgDllName>
|
||||||
|
<TargetDlgDllArguments>-pLPC1768</TargetDlgDllArguments>
|
||||||
|
</DllOpt>
|
||||||
|
<DebugOpt>
|
||||||
|
<uSim>1</uSim>
|
||||||
|
<uTrg>0</uTrg>
|
||||||
|
<sLdApp>1</sLdApp>
|
||||||
|
<sGomain>1</sGomain>
|
||||||
|
<sRbreak>1</sRbreak>
|
||||||
|
<sRwatch>1</sRwatch>
|
||||||
|
<sRmem>1</sRmem>
|
||||||
|
<sRfunc>1</sRfunc>
|
||||||
|
<sRbox>1</sRbox>
|
||||||
|
<tLdApp>1</tLdApp>
|
||||||
|
<tGomain>0</tGomain>
|
||||||
|
<tRbreak>1</tRbreak>
|
||||||
|
<tRwatch>1</tRwatch>
|
||||||
|
<tRmem>1</tRmem>
|
||||||
|
<tRfunc>0</tRfunc>
|
||||||
|
<tRbox>1</tRbox>
|
||||||
|
<tRtrace>1</tRtrace>
|
||||||
|
<sRunDeb>0</sRunDeb>
|
||||||
|
<sLrtime>0</sLrtime>
|
||||||
|
<nTsel>1</nTsel>
|
||||||
|
<sDll></sDll>
|
||||||
|
<sDllPa></sDllPa>
|
||||||
|
<sDlgDll></sDlgDll>
|
||||||
|
<sDlgPa></sDlgPa>
|
||||||
|
<sIfile></sIfile>
|
||||||
|
<tDll></tDll>
|
||||||
|
<tDllPa></tDllPa>
|
||||||
|
<tDlgDll></tDlgDll>
|
||||||
|
<tDlgPa></tDlgPa>
|
||||||
|
<tIfile></tIfile>
|
||||||
|
<pMon>BIN\UL2CM3.DLL</pMon>
|
||||||
|
</DebugOpt>
|
||||||
|
<TargetDriverDllRegistry>
|
||||||
|
<SetRegEntry>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Key>DLGDARM</Key>
|
||||||
|
<Name>(1010=-1,-1,-1,-1,0)(1007=-1,-1,-1,-1,0)(1008=-1,-1,-1,-1,0)(1009=-1,-1,-1,-1,0)(1012=-1,-1,-1,-1,0)(350=-1,-1,-1,-1,0)(250=-1,-1,-1,-1,0)(270=-1,-1,-1,-1,0)(313=-1,-1,-1,-1,0)(291=-1,-1,-1,-1,0)(302=-1,-1,-1,-1,0)(110=-1,-1,-1,-1,0)(113=-1,-1,-1,-1,0)(320=-1,-1,-1,-1,0)(210=-1,-1,-1,-1,0)(330=-1,-1,-1,-1,0)(332=-1,-1,-1,-1,0)(333=-1,-1,-1,-1,0)(334=-1,-1,-1,-1,0)(335=-1,-1,-1,-1,0)(336=-1,-1,-1,-1,0)(345=-1,-1,-1,-1,0)(346=-1,-1,-1,-1,0)(381=-1,-1,-1,-1,0)(382=-1,-1,-1,-1,0)(383=-1,-1,-1,-1,0)(384=-1,-1,-1,-1,0)(197=-1,-1,-1,-1,0)(198=-1,-1,-1,-1,0)(191=-1,-1,-1,-1,0)(192=-1,-1,-1,-1,0)(199=-1,-1,-1,-1,0)(180=-1,-1,-1,-1,0)(261=-1,-1,-1,-1,0)(262=-1,-1,-1,-1,0)(231=-1,-1,-1,-1,0)(232=-1,-1,-1,-1,0)(233=-1,-1,-1,-1,0)(121=-1,-1,-1,-1,0)(122=-1,-1,-1,-1,0)(123=-1,-1,-1,-1,0)(124=-1,-1,-1,-1,0)(170=-1,-1,-1,-1,0)(142=-1,-1,-1,-1,0)(150=-1,-1,-1,-1,0)(400=-1,-1,-1,-1,0)(370=-1,-1,-1,-1,0)(160=-1,-1,-1,-1,0)(280=-1,-1,-1,-1,0)(240=-1,-1,-1,-1,0)</Name>
|
||||||
|
</SetRegEntry>
|
||||||
|
<SetRegEntry>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Key>ARMDBGFLAGS</Key>
|
||||||
|
<Name>-T0</Name>
|
||||||
|
</SetRegEntry>
|
||||||
|
<SetRegEntry>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Key>UL2CM3</Key>
|
||||||
|
<Name>-O463 -S0 -C0 -FO7 -FD10000000 -FC800 -FN1 -FF0LPC_IAP_512 -FS00 -FL080000)</Name>
|
||||||
|
</SetRegEntry>
|
||||||
|
</TargetDriverDllRegistry>
|
||||||
|
<Breakpoint/>
|
||||||
|
<MemoryWindow1>
|
||||||
|
<Mm>
|
||||||
|
<WinNumber>1</WinNumber>
|
||||||
|
<SubType>0</SubType>
|
||||||
|
<ItemText>0x000000A</ItemText>
|
||||||
|
</Mm>
|
||||||
|
</MemoryWindow1>
|
||||||
|
<DebugFlag>
|
||||||
|
<trace>0</trace>
|
||||||
|
<periodic>1</periodic>
|
||||||
|
<aLwin>1</aLwin>
|
||||||
|
<aCover>0</aCover>
|
||||||
|
<aSer1>0</aSer1>
|
||||||
|
<aSer2>0</aSer2>
|
||||||
|
<aPa>0</aPa>
|
||||||
|
<viewmode>1</viewmode>
|
||||||
|
<vrSel>0</vrSel>
|
||||||
|
<aSym>0</aSym>
|
||||||
|
<aTbox>0</aTbox>
|
||||||
|
<AscS1>0</AscS1>
|
||||||
|
<AscS2>0</AscS2>
|
||||||
|
<AscS3>0</AscS3>
|
||||||
|
<aSer3>0</aSer3>
|
||||||
|
<eProf>0</eProf>
|
||||||
|
<aLa>0</aLa>
|
||||||
|
<aPa1>0</aPa1>
|
||||||
|
<AscS4>0</AscS4>
|
||||||
|
<aSer4>0</aSer4>
|
||||||
|
<StkLoc>0</StkLoc>
|
||||||
|
<TrcWin>0</TrcWin>
|
||||||
|
<newCpu>0</newCpu>
|
||||||
|
<uProt>0</uProt>
|
||||||
|
</DebugFlag>
|
||||||
|
<Tracepoint>
|
||||||
|
<THDelay>0</THDelay>
|
||||||
|
</Tracepoint>
|
||||||
|
<LintExecutable></LintExecutable>
|
||||||
|
<LintConfigFile></LintConfigFile>
|
||||||
|
</TargetOption>
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
<Group>
|
||||||
|
<GroupName>Source Group 1</GroupName>
|
||||||
|
<tvExp>1</tvExp>
|
||||||
|
<tvExpOptDlg>0</tvExpOptDlg>
|
||||||
|
<cbSel>0</cbSel>
|
||||||
|
<RteFlg>0</RteFlg>
|
||||||
|
<File>
|
||||||
|
<GroupNumber>1</GroupNumber>
|
||||||
|
<FileNumber>1</FileNumber>
|
||||||
|
<FileType>2</FileType>
|
||||||
|
<tvExp>0</tvExp>
|
||||||
|
<Focus>0</Focus>
|
||||||
|
<ColumnNumber>0</ColumnNumber>
|
||||||
|
<tvExpOptDlg>0</tvExpOptDlg>
|
||||||
|
<TopLine>1</TopLine>
|
||||||
|
<CurrentLine>11</CurrentLine>
|
||||||
|
<bDave2>0</bDave2>
|
||||||
|
<PathWithFileName>.\DATATRANSFER.asm</PathWithFileName>
|
||||||
|
<FilenameWithoutPath>DATATRANSFER.asm</FilenameWithoutPath>
|
||||||
|
<RteFlg>0</RteFlg>
|
||||||
|
<bShared>0</bShared>
|
||||||
|
</File>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
</ProjectOpt>
|
405
ES/Lab/Lab1/Init/init.uvproj
Normal file
405
ES/Lab/Lab1/Init/init.uvproj
Normal file
|
@ -0,0 +1,405 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
|
||||||
|
<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="project_proj.xsd">
|
||||||
|
|
||||||
|
<SchemaVersion>1.1</SchemaVersion>
|
||||||
|
|
||||||
|
<Header>### uVision Project, (C) Keil Software</Header>
|
||||||
|
|
||||||
|
<Targets>
|
||||||
|
<Target>
|
||||||
|
<TargetName>Target 1</TargetName>
|
||||||
|
<ToolsetNumber>0x4</ToolsetNumber>
|
||||||
|
<ToolsetName>ARM-ADS</ToolsetName>
|
||||||
|
<TargetOption>
|
||||||
|
<TargetCommonOption>
|
||||||
|
<Device>LPC1768</Device>
|
||||||
|
<Vendor>NXP (founded by Philips)</Vendor>
|
||||||
|
<Cpu>IRAM(0x10000000-0x10007FFF) IRAM2(0x2007C000-0x20083FFF) IROM(0-0x7FFFF) CLOCK(12000000) CPUTYPE("Cortex-M3")</Cpu>
|
||||||
|
<FlashUtilSpec></FlashUtilSpec>
|
||||||
|
<StartupFile>"STARTUP\NXP\LPC17xx\startup_LPC17xx.s" ("NXP LPC17xx Startup Code")</StartupFile>
|
||||||
|
<FlashDriverDll>UL2CM3(-O463 -S0 -C0 -FO7 -FD10000000 -FC800 -FN1 -FF0LPC_IAP_512 -FS00 -FL080000)</FlashDriverDll>
|
||||||
|
<DeviceId>4868</DeviceId>
|
||||||
|
<RegisterFile>LPC17xx.H</RegisterFile>
|
||||||
|
<MemoryEnv></MemoryEnv>
|
||||||
|
<Cmp></Cmp>
|
||||||
|
<Asm></Asm>
|
||||||
|
<Linker></Linker>
|
||||||
|
<OHString></OHString>
|
||||||
|
<InfinionOptionDll></InfinionOptionDll>
|
||||||
|
<SLE66CMisc></SLE66CMisc>
|
||||||
|
<SLE66AMisc></SLE66AMisc>
|
||||||
|
<SLE66LinkerMisc></SLE66LinkerMisc>
|
||||||
|
<SFDFile></SFDFile>
|
||||||
|
<UseEnv>0</UseEnv>
|
||||||
|
<BinPath></BinPath>
|
||||||
|
<IncludePath></IncludePath>
|
||||||
|
<LibPath></LibPath>
|
||||||
|
<RegisterFilePath>NXP\LPC17xx\</RegisterFilePath>
|
||||||
|
<DBRegisterFilePath>NXP\LPC17xx\</DBRegisterFilePath>
|
||||||
|
<TargetStatus>
|
||||||
|
<Error>0</Error>
|
||||||
|
<ExitCodeStop>0</ExitCodeStop>
|
||||||
|
<ButtonStop>0</ButtonStop>
|
||||||
|
<NotGenerated>0</NotGenerated>
|
||||||
|
<InvalidFlash>1</InvalidFlash>
|
||||||
|
</TargetStatus>
|
||||||
|
<OutputDirectory>.\</OutputDirectory>
|
||||||
|
<OutputName>init</OutputName>
|
||||||
|
<CreateExecutable>1</CreateExecutable>
|
||||||
|
<CreateLib>0</CreateLib>
|
||||||
|
<CreateHexFile>0</CreateHexFile>
|
||||||
|
<DebugInformation>1</DebugInformation>
|
||||||
|
<BrowseInformation>1</BrowseInformation>
|
||||||
|
<ListingPath>.\</ListingPath>
|
||||||
|
<HexFormatSelection>1</HexFormatSelection>
|
||||||
|
<Merge32K>0</Merge32K>
|
||||||
|
<CreateBatchFile>0</CreateBatchFile>
|
||||||
|
<BeforeCompile>
|
||||||
|
<RunUserProg1>0</RunUserProg1>
|
||||||
|
<RunUserProg2>0</RunUserProg2>
|
||||||
|
<UserProg1Name></UserProg1Name>
|
||||||
|
<UserProg2Name></UserProg2Name>
|
||||||
|
<UserProg1Dos16Mode>0</UserProg1Dos16Mode>
|
||||||
|
<UserProg2Dos16Mode>0</UserProg2Dos16Mode>
|
||||||
|
<nStopU1X>0</nStopU1X>
|
||||||
|
<nStopU2X>0</nStopU2X>
|
||||||
|
</BeforeCompile>
|
||||||
|
<BeforeMake>
|
||||||
|
<RunUserProg1>0</RunUserProg1>
|
||||||
|
<RunUserProg2>0</RunUserProg2>
|
||||||
|
<UserProg1Name></UserProg1Name>
|
||||||
|
<UserProg2Name></UserProg2Name>
|
||||||
|
<UserProg1Dos16Mode>0</UserProg1Dos16Mode>
|
||||||
|
<UserProg2Dos16Mode>0</UserProg2Dos16Mode>
|
||||||
|
</BeforeMake>
|
||||||
|
<AfterMake>
|
||||||
|
<RunUserProg1>0</RunUserProg1>
|
||||||
|
<RunUserProg2>0</RunUserProg2>
|
||||||
|
<UserProg1Name></UserProg1Name>
|
||||||
|
<UserProg2Name></UserProg2Name>
|
||||||
|
<UserProg1Dos16Mode>0</UserProg1Dos16Mode>
|
||||||
|
<UserProg2Dos16Mode>0</UserProg2Dos16Mode>
|
||||||
|
</AfterMake>
|
||||||
|
<SelectedForBatchBuild>0</SelectedForBatchBuild>
|
||||||
|
<SVCSIdString></SVCSIdString>
|
||||||
|
</TargetCommonOption>
|
||||||
|
<CommonProperty>
|
||||||
|
<UseCPPCompiler>0</UseCPPCompiler>
|
||||||
|
<RVCTCodeConst>0</RVCTCodeConst>
|
||||||
|
<RVCTZI>0</RVCTZI>
|
||||||
|
<RVCTOtherData>0</RVCTOtherData>
|
||||||
|
<ModuleSelection>0</ModuleSelection>
|
||||||
|
<IncludeInBuild>1</IncludeInBuild>
|
||||||
|
<AlwaysBuild>0</AlwaysBuild>
|
||||||
|
<GenerateAssemblyFile>0</GenerateAssemblyFile>
|
||||||
|
<AssembleAssemblyFile>0</AssembleAssemblyFile>
|
||||||
|
<PublicsOnly>0</PublicsOnly>
|
||||||
|
<StopOnExitCode>3</StopOnExitCode>
|
||||||
|
<CustomArgument></CustomArgument>
|
||||||
|
<IncludeLibraryModules></IncludeLibraryModules>
|
||||||
|
</CommonProperty>
|
||||||
|
<DllOption>
|
||||||
|
<SimDllName>SARMCM3.DLL</SimDllName>
|
||||||
|
<SimDllArguments>-MPU</SimDllArguments>
|
||||||
|
<SimDlgDll>DARMP1.DLL</SimDlgDll>
|
||||||
|
<SimDlgDllArguments>-pLPC1768</SimDlgDllArguments>
|
||||||
|
<TargetDllName>SARMCM3.DLL</TargetDllName>
|
||||||
|
<TargetDllArguments>-MPU</TargetDllArguments>
|
||||||
|
<TargetDlgDll>TARMP1.DLL</TargetDlgDll>
|
||||||
|
<TargetDlgDllArguments>-pLPC1768</TargetDlgDllArguments>
|
||||||
|
</DllOption>
|
||||||
|
<DebugOption>
|
||||||
|
<OPTHX>
|
||||||
|
<HexSelection>1</HexSelection>
|
||||||
|
<HexRangeLowAddress>0</HexRangeLowAddress>
|
||||||
|
<HexRangeHighAddress>0</HexRangeHighAddress>
|
||||||
|
<HexOffset>0</HexOffset>
|
||||||
|
<Oh166RecLen>16</Oh166RecLen>
|
||||||
|
</OPTHX>
|
||||||
|
<Simulator>
|
||||||
|
<UseSimulator>1</UseSimulator>
|
||||||
|
<LoadApplicationAtStartup>1</LoadApplicationAtStartup>
|
||||||
|
<RunToMain>1</RunToMain>
|
||||||
|
<RestoreBreakpoints>1</RestoreBreakpoints>
|
||||||
|
<RestoreWatchpoints>1</RestoreWatchpoints>
|
||||||
|
<RestoreMemoryDisplay>1</RestoreMemoryDisplay>
|
||||||
|
<RestoreFunctions>1</RestoreFunctions>
|
||||||
|
<RestoreToolbox>1</RestoreToolbox>
|
||||||
|
<LimitSpeedToRealTime>0</LimitSpeedToRealTime>
|
||||||
|
</Simulator>
|
||||||
|
<Target>
|
||||||
|
<UseTarget>0</UseTarget>
|
||||||
|
<LoadApplicationAtStartup>1</LoadApplicationAtStartup>
|
||||||
|
<RunToMain>0</RunToMain>
|
||||||
|
<RestoreBreakpoints>1</RestoreBreakpoints>
|
||||||
|
<RestoreWatchpoints>1</RestoreWatchpoints>
|
||||||
|
<RestoreMemoryDisplay>1</RestoreMemoryDisplay>
|
||||||
|
<RestoreFunctions>0</RestoreFunctions>
|
||||||
|
<RestoreToolbox>1</RestoreToolbox>
|
||||||
|
<RestoreTracepoints>1</RestoreTracepoints>
|
||||||
|
</Target>
|
||||||
|
<RunDebugAfterBuild>0</RunDebugAfterBuild>
|
||||||
|
<TargetSelection>1</TargetSelection>
|
||||||
|
<SimDlls>
|
||||||
|
<CpuDll></CpuDll>
|
||||||
|
<CpuDllArguments></CpuDllArguments>
|
||||||
|
<PeripheralDll></PeripheralDll>
|
||||||
|
<PeripheralDllArguments></PeripheralDllArguments>
|
||||||
|
<InitializationFile></InitializationFile>
|
||||||
|
</SimDlls>
|
||||||
|
<TargetDlls>
|
||||||
|
<CpuDll></CpuDll>
|
||||||
|
<CpuDllArguments></CpuDllArguments>
|
||||||
|
<PeripheralDll></PeripheralDll>
|
||||||
|
<PeripheralDllArguments></PeripheralDllArguments>
|
||||||
|
<InitializationFile></InitializationFile>
|
||||||
|
<Driver>BIN\UL2CM3.DLL</Driver>
|
||||||
|
</TargetDlls>
|
||||||
|
</DebugOption>
|
||||||
|
<Utilities>
|
||||||
|
<Flash1>
|
||||||
|
<UseTargetDll>1</UseTargetDll>
|
||||||
|
<UseExternalTool>0</UseExternalTool>
|
||||||
|
<RunIndependent>0</RunIndependent>
|
||||||
|
<UpdateFlashBeforeDebugging>1</UpdateFlashBeforeDebugging>
|
||||||
|
<Capability>0</Capability>
|
||||||
|
<DriverSelection>-1</DriverSelection>
|
||||||
|
</Flash1>
|
||||||
|
<Flash2>BIN\UL2CM3.DLL</Flash2>
|
||||||
|
<Flash3></Flash3>
|
||||||
|
<Flash4></Flash4>
|
||||||
|
</Utilities>
|
||||||
|
<TargetArmAds>
|
||||||
|
<ArmAdsMisc>
|
||||||
|
<GenerateListings>0</GenerateListings>
|
||||||
|
<asHll>1</asHll>
|
||||||
|
<asAsm>1</asAsm>
|
||||||
|
<asMacX>1</asMacX>
|
||||||
|
<asSyms>1</asSyms>
|
||||||
|
<asFals>1</asFals>
|
||||||
|
<asDbgD>1</asDbgD>
|
||||||
|
<asForm>1</asForm>
|
||||||
|
<ldLst>0</ldLst>
|
||||||
|
<ldmm>1</ldmm>
|
||||||
|
<ldXref>1</ldXref>
|
||||||
|
<BigEnd>0</BigEnd>
|
||||||
|
<AdsALst>1</AdsALst>
|
||||||
|
<AdsACrf>1</AdsACrf>
|
||||||
|
<AdsANop>0</AdsANop>
|
||||||
|
<AdsANot>0</AdsANot>
|
||||||
|
<AdsLLst>1</AdsLLst>
|
||||||
|
<AdsLmap>1</AdsLmap>
|
||||||
|
<AdsLcgr>1</AdsLcgr>
|
||||||
|
<AdsLsym>1</AdsLsym>
|
||||||
|
<AdsLszi>1</AdsLszi>
|
||||||
|
<AdsLtoi>1</AdsLtoi>
|
||||||
|
<AdsLsun>1</AdsLsun>
|
||||||
|
<AdsLven>1</AdsLven>
|
||||||
|
<AdsLsxf>1</AdsLsxf>
|
||||||
|
<RvctClst>0</RvctClst>
|
||||||
|
<GenPPlst>0</GenPPlst>
|
||||||
|
<AdsCpuType>"Cortex-M3"</AdsCpuType>
|
||||||
|
<RvctDeviceName></RvctDeviceName>
|
||||||
|
<mOS>0</mOS>
|
||||||
|
<uocRom>0</uocRom>
|
||||||
|
<uocRam>0</uocRam>
|
||||||
|
<hadIROM>1</hadIROM>
|
||||||
|
<hadIRAM>1</hadIRAM>
|
||||||
|
<hadXRAM>0</hadXRAM>
|
||||||
|
<uocXRam>0</uocXRam>
|
||||||
|
<RvdsVP>0</RvdsVP>
|
||||||
|
<hadIRAM2>1</hadIRAM2>
|
||||||
|
<hadIROM2>0</hadIROM2>
|
||||||
|
<StupSel>8</StupSel>
|
||||||
|
<useUlib>0</useUlib>
|
||||||
|
<EndSel>0</EndSel>
|
||||||
|
<uLtcg>0</uLtcg>
|
||||||
|
<RoSelD>3</RoSelD>
|
||||||
|
<RwSelD>3</RwSelD>
|
||||||
|
<CodeSel>0</CodeSel>
|
||||||
|
<OptFeed>0</OptFeed>
|
||||||
|
<NoZi1>0</NoZi1>
|
||||||
|
<NoZi2>0</NoZi2>
|
||||||
|
<NoZi3>0</NoZi3>
|
||||||
|
<NoZi4>0</NoZi4>
|
||||||
|
<NoZi5>0</NoZi5>
|
||||||
|
<Ro1Chk>0</Ro1Chk>
|
||||||
|
<Ro2Chk>0</Ro2Chk>
|
||||||
|
<Ro3Chk>0</Ro3Chk>
|
||||||
|
<Ir1Chk>1</Ir1Chk>
|
||||||
|
<Ir2Chk>0</Ir2Chk>
|
||||||
|
<Ra1Chk>0</Ra1Chk>
|
||||||
|
<Ra2Chk>0</Ra2Chk>
|
||||||
|
<Ra3Chk>0</Ra3Chk>
|
||||||
|
<Im1Chk>1</Im1Chk>
|
||||||
|
<Im2Chk>0</Im2Chk>
|
||||||
|
<OnChipMemories>
|
||||||
|
<Ocm1>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</Ocm1>
|
||||||
|
<Ocm2>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</Ocm2>
|
||||||
|
<Ocm3>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</Ocm3>
|
||||||
|
<Ocm4>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</Ocm4>
|
||||||
|
<Ocm5>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</Ocm5>
|
||||||
|
<Ocm6>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</Ocm6>
|
||||||
|
<IRAM>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x10000000</StartAddress>
|
||||||
|
<Size>0x8000</Size>
|
||||||
|
</IRAM>
|
||||||
|
<IROM>
|
||||||
|
<Type>1</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x80000</Size>
|
||||||
|
</IROM>
|
||||||
|
<XRAM>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</XRAM>
|
||||||
|
<OCR_RVCT1>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</OCR_RVCT1>
|
||||||
|
<OCR_RVCT2>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</OCR_RVCT2>
|
||||||
|
<OCR_RVCT3>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</OCR_RVCT3>
|
||||||
|
<OCR_RVCT4>
|
||||||
|
<Type>1</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x80000</Size>
|
||||||
|
</OCR_RVCT4>
|
||||||
|
<OCR_RVCT5>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</OCR_RVCT5>
|
||||||
|
<OCR_RVCT6>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</OCR_RVCT6>
|
||||||
|
<OCR_RVCT7>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</OCR_RVCT7>
|
||||||
|
<OCR_RVCT8>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x0</StartAddress>
|
||||||
|
<Size>0x0</Size>
|
||||||
|
</OCR_RVCT8>
|
||||||
|
<OCR_RVCT9>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x10000000</StartAddress>
|
||||||
|
<Size>0x8000</Size>
|
||||||
|
</OCR_RVCT9>
|
||||||
|
<OCR_RVCT10>
|
||||||
|
<Type>0</Type>
|
||||||
|
<StartAddress>0x2007c000</StartAddress>
|
||||||
|
<Size>0x8000</Size>
|
||||||
|
</OCR_RVCT10>
|
||||||
|
</OnChipMemories>
|
||||||
|
<RvctStartVector></RvctStartVector>
|
||||||
|
</ArmAdsMisc>
|
||||||
|
<Cads>
|
||||||
|
<interw>1</interw>
|
||||||
|
<Optim>1</Optim>
|
||||||
|
<oTime>0</oTime>
|
||||||
|
<SplitLS>0</SplitLS>
|
||||||
|
<OneElfS>0</OneElfS>
|
||||||
|
<Strict>0</Strict>
|
||||||
|
<EnumInt>0</EnumInt>
|
||||||
|
<PlainCh>0</PlainCh>
|
||||||
|
<Ropi>0</Ropi>
|
||||||
|
<Rwpi>0</Rwpi>
|
||||||
|
<wLevel>0</wLevel>
|
||||||
|
<uThumb>0</uThumb>
|
||||||
|
<uSurpInc>0</uSurpInc>
|
||||||
|
<VariousControls>
|
||||||
|
<MiscControls></MiscControls>
|
||||||
|
<Define></Define>
|
||||||
|
<Undefine></Undefine>
|
||||||
|
<IncludePath></IncludePath>
|
||||||
|
</VariousControls>
|
||||||
|
</Cads>
|
||||||
|
<Aads>
|
||||||
|
<interw>1</interw>
|
||||||
|
<Ropi>0</Ropi>
|
||||||
|
<Rwpi>0</Rwpi>
|
||||||
|
<thumb>0</thumb>
|
||||||
|
<SplitLS>0</SplitLS>
|
||||||
|
<SwStkChk>0</SwStkChk>
|
||||||
|
<NoWarn>0</NoWarn>
|
||||||
|
<uSurpInc>0</uSurpInc>
|
||||||
|
<VariousControls>
|
||||||
|
<MiscControls></MiscControls>
|
||||||
|
<Define></Define>
|
||||||
|
<Undefine></Undefine>
|
||||||
|
<IncludePath></IncludePath>
|
||||||
|
</VariousControls>
|
||||||
|
</Aads>
|
||||||
|
<LDads>
|
||||||
|
<umfTarg>0</umfTarg>
|
||||||
|
<Ropi>0</Ropi>
|
||||||
|
<Rwpi>0</Rwpi>
|
||||||
|
<noStLib>0</noStLib>
|
||||||
|
<RepFail>1</RepFail>
|
||||||
|
<useFile>0</useFile>
|
||||||
|
<TextAddressRange>0x00000000</TextAddressRange>
|
||||||
|
<DataAddressRange>0x10000000</DataAddressRange>
|
||||||
|
<ScatterFile></ScatterFile>
|
||||||
|
<IncludeLibs></IncludeLibs>
|
||||||
|
<IncludeLibsPath></IncludeLibsPath>
|
||||||
|
<Misc></Misc>
|
||||||
|
<LinkerInputFile></LinkerInputFile>
|
||||||
|
<DisabledWarnings></DisabledWarnings>
|
||||||
|
</LDads>
|
||||||
|
</TargetArmAds>
|
||||||
|
</TargetOption>
|
||||||
|
<Groups>
|
||||||
|
<Group>
|
||||||
|
<GroupName>Source Group 1</GroupName>
|
||||||
|
<Files>
|
||||||
|
<File>
|
||||||
|
<FileName>DATATRANSFER.asm</FileName>
|
||||||
|
<FileType>2</FileType>
|
||||||
|
<FilePath>.\DATATRANSFER.asm</FilePath>
|
||||||
|
</File>
|
||||||
|
</Files>
|
||||||
|
</Group>
|
||||||
|
</Groups>
|
||||||
|
</Target>
|
||||||
|
</Targets>
|
||||||
|
|
||||||
|
</Project>
|
2
ES/Lab/Lab1/Init/init_Target 1.dep
Normal file
2
ES/Lab/Lab1/Init/init_Target 1.dep
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
Dependencies for Project 'init', Target 'Target 1': (DO NOT MODIFY !)
|
||||||
|
F (.\DATATRANSFER.asm)(0x6881DFCC)(--cpu Cortex-M3 --pd "__EVAL SETA 1" -g --apcs=interwork
-I C:\Keil\ARM\RV31\INC
-I C:\Keil\ARM\CMSIS\Include
-I C:\Keil\ARM\Inc\NXP\LPC17xx
--list "DATATRANSFER.lst" --xref -o "DATATRANSFER.o" --depend "DATATRANSFER.d")
|
249
ES/Lab/Lab1/Init/init_uvopt.bak
Normal file
249
ES/Lab/Lab1/Init/init_uvopt.bak
Normal file
|
@ -0,0 +1,249 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
|
||||||
|
<ProjectOpt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="project_opt.xsd">
|
||||||
|
|
||||||
|
<SchemaVersion>1.0</SchemaVersion>
|
||||||
|
|
||||||
|
<Header>### uVision Project, (C) Keil Software</Header>
|
||||||
|
|
||||||
|
<Extensions>
|
||||||
|
<cExt>*.c</cExt>
|
||||||
|
<aExt>*.s*; *.src; *.a*</aExt>
|
||||||
|
<oExt>*.obj</oExt>
|
||||||
|
<lExt>*.lib</lExt>
|
||||||
|
<tExt>*.txt; *.h; *.inc</tExt>
|
||||||
|
<pExt>*.plm</pExt>
|
||||||
|
<CppX>*.cpp</CppX>
|
||||||
|
</Extensions>
|
||||||
|
|
||||||
|
<DaveTm>
|
||||||
|
<dwLowDateTime>0</dwLowDateTime>
|
||||||
|
<dwHighDateTime>0</dwHighDateTime>
|
||||||
|
</DaveTm>
|
||||||
|
|
||||||
|
<Target>
|
||||||
|
<TargetName>Target 1</TargetName>
|
||||||
|
<ToolsetNumber>0x4</ToolsetNumber>
|
||||||
|
<ToolsetName>ARM-ADS</ToolsetName>
|
||||||
|
<TargetOption>
|
||||||
|
<CLKADS>12000000</CLKADS>
|
||||||
|
<OPTTT>
|
||||||
|
<gFlags>0</gFlags>
|
||||||
|
<BeepAtEnd>1</BeepAtEnd>
|
||||||
|
<RunSim>1</RunSim>
|
||||||
|
<RunTarget>0</RunTarget>
|
||||||
|
</OPTTT>
|
||||||
|
<OPTHX>
|
||||||
|
<HexSelection>1</HexSelection>
|
||||||
|
<FlashByte>65535</FlashByte>
|
||||||
|
<HexRangeLowAddress>0</HexRangeLowAddress>
|
||||||
|
<HexRangeHighAddress>0</HexRangeHighAddress>
|
||||||
|
<HexOffset>0</HexOffset>
|
||||||
|
</OPTHX>
|
||||||
|
<OPTLEX>
|
||||||
|
<PageWidth>79</PageWidth>
|
||||||
|
<PageLength>66</PageLength>
|
||||||
|
<TabStop>8</TabStop>
|
||||||
|
<ListingPath>.\</ListingPath>
|
||||||
|
</OPTLEX>
|
||||||
|
<ListingPage>
|
||||||
|
<CreateCListing>1</CreateCListing>
|
||||||
|
<CreateAListing>1</CreateAListing>
|
||||||
|
<CreateLListing>1</CreateLListing>
|
||||||
|
<CreateIListing>0</CreateIListing>
|
||||||
|
<AsmCond>1</AsmCond>
|
||||||
|
<AsmSymb>1</AsmSymb>
|
||||||
|
<AsmXref>0</AsmXref>
|
||||||
|
<CCond>1</CCond>
|
||||||
|
<CCode>0</CCode>
|
||||||
|
<CListInc>0</CListInc>
|
||||||
|
<CSymb>0</CSymb>
|
||||||
|
<LinkerCodeListing>0</LinkerCodeListing>
|
||||||
|
</ListingPage>
|
||||||
|
<OPTXL>
|
||||||
|
<LMap>1</LMap>
|
||||||
|
<LComments>1</LComments>
|
||||||
|
<LGenerateSymbols>1</LGenerateSymbols>
|
||||||
|
<LLibSym>1</LLibSym>
|
||||||
|
<LLines>1</LLines>
|
||||||
|
<LLocSym>1</LLocSym>
|
||||||
|
<LPubSym>1</LPubSym>
|
||||||
|
<LXref>0</LXref>
|
||||||
|
<LExpSel>0</LExpSel>
|
||||||
|
</OPTXL>
|
||||||
|
<OPTFL>
|
||||||
|
<tvExp>1</tvExp>
|
||||||
|
<tvExpOptDlg>0</tvExpOptDlg>
|
||||||
|
<IsCurrentTarget>1</IsCurrentTarget>
|
||||||
|
</OPTFL>
|
||||||
|
<CpuCode>8</CpuCode>
|
||||||
|
<Books>
|
||||||
|
<Book>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Title>Data Sheet</Title>
|
||||||
|
<Path>DATASHTS\PHILIPS\LPC176x_DS.pdf</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>1</Number>
|
||||||
|
<Title>User Manual</Title>
|
||||||
|
<Path>DATASHTS\PHILIPS\LPC17xx_UM.pdf</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>2</Number>
|
||||||
|
<Title>Errata Sheet</Title>
|
||||||
|
<Path>DATASHTS\PHILIPS\LPC1768_ES.pdf</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>3</Number>
|
||||||
|
<Title>Technical Reference Manual</Title>
|
||||||
|
<Path>datashts\arm\cortex_m3\r2p1\DDI0337I_CORTEXM3_R2P1_TRM.PDF</Path>
|
||||||
|
</Book>
|
||||||
|
<Book>
|
||||||
|
<Number>4</Number>
|
||||||
|
<Title>Generic User Guide</Title>
|
||||||
|
<Path>datashts\arm\cortex_m3\r2p1\DUI0552A_CORTEX_M3_DGUG.PDF</Path>
|
||||||
|
</Book>
|
||||||
|
</Books>
|
||||||
|
<DllOpt>
|
||||||
|
<SimDllName>SARMCM3.DLL</SimDllName>
|
||||||
|
<SimDllArguments>-MPU</SimDllArguments>
|
||||||
|
<SimDlgDllName>DARMP1.DLL</SimDlgDllName>
|
||||||
|
<SimDlgDllArguments>-pLPC1768</SimDlgDllArguments>
|
||||||
|
<TargetDllName>SARMCM3.DLL</TargetDllName>
|
||||||
|
<TargetDllArguments>-MPU</TargetDllArguments>
|
||||||
|
<TargetDlgDllName>TARMP1.DLL</TargetDlgDllName>
|
||||||
|
<TargetDlgDllArguments>-pLPC1768</TargetDlgDllArguments>
|
||||||
|
</DllOpt>
|
||||||
|
<DebugOpt>
|
||||||
|
<uSim>1</uSim>
|
||||||
|
<uTrg>0</uTrg>
|
||||||
|
<sLdApp>1</sLdApp>
|
||||||
|
<sGomain>1</sGomain>
|
||||||
|
<sRbreak>1</sRbreak>
|
||||||
|
<sRwatch>1</sRwatch>
|
||||||
|
<sRmem>1</sRmem>
|
||||||
|
<sRfunc>1</sRfunc>
|
||||||
|
<sRbox>1</sRbox>
|
||||||
|
<tLdApp>1</tLdApp>
|
||||||
|
<tGomain>0</tGomain>
|
||||||
|
<tRbreak>1</tRbreak>
|
||||||
|
<tRwatch>1</tRwatch>
|
||||||
|
<tRmem>1</tRmem>
|
||||||
|
<tRfunc>0</tRfunc>
|
||||||
|
<tRbox>1</tRbox>
|
||||||
|
<tRtrace>1</tRtrace>
|
||||||
|
<sRunDeb>0</sRunDeb>
|
||||||
|
<sLrtime>0</sLrtime>
|
||||||
|
<nTsel>1</nTsel>
|
||||||
|
<sDll></sDll>
|
||||||
|
<sDllPa></sDllPa>
|
||||||
|
<sDlgDll></sDlgDll>
|
||||||
|
<sDlgPa></sDlgPa>
|
||||||
|
<sIfile></sIfile>
|
||||||
|
<tDll></tDll>
|
||||||
|
<tDllPa></tDllPa>
|
||||||
|
<tDlgDll></tDlgDll>
|
||||||
|
<tDlgPa></tDlgPa>
|
||||||
|
<tIfile></tIfile>
|
||||||
|
<pMon>BIN\UL2CM3.DLL</pMon>
|
||||||
|
</DebugOpt>
|
||||||
|
<TargetDriverDllRegistry>
|
||||||
|
<SetRegEntry>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Key>DLGDARM</Key>
|
||||||
|
<Name>(1010=-1,-1,-1,-1,0)(1007=-1,-1,-1,-1,0)(1008=-1,-1,-1,-1,0)(1009=-1,-1,-1,-1,0)(1012=-1,-1,-1,-1,0)(350=-1,-1,-1,-1,0)(250=-1,-1,-1,-1,0)(270=-1,-1,-1,-1,0)(313=-1,-1,-1,-1,0)(291=-1,-1,-1,-1,0)(302=-1,-1,-1,-1,0)(110=-1,-1,-1,-1,0)(113=-1,-1,-1,-1,0)(320=-1,-1,-1,-1,0)(210=-1,-1,-1,-1,0)(330=-1,-1,-1,-1,0)(332=-1,-1,-1,-1,0)(333=-1,-1,-1,-1,0)(334=-1,-1,-1,-1,0)(335=-1,-1,-1,-1,0)(336=-1,-1,-1,-1,0)(345=-1,-1,-1,-1,0)(346=-1,-1,-1,-1,0)(381=-1,-1,-1,-1,0)(382=-1,-1,-1,-1,0)(383=-1,-1,-1,-1,0)(384=-1,-1,-1,-1,0)(197=-1,-1,-1,-1,0)(198=-1,-1,-1,-1,0)(191=-1,-1,-1,-1,0)(192=-1,-1,-1,-1,0)(199=-1,-1,-1,-1,0)(180=-1,-1,-1,-1,0)(261=-1,-1,-1,-1,0)(262=-1,-1,-1,-1,0)(231=-1,-1,-1,-1,0)(232=-1,-1,-1,-1,0)(233=-1,-1,-1,-1,0)(121=-1,-1,-1,-1,0)(122=-1,-1,-1,-1,0)(123=-1,-1,-1,-1,0)(124=-1,-1,-1,-1,0)(170=-1,-1,-1,-1,0)(142=-1,-1,-1,-1,0)(150=-1,-1,-1,-1,0)(400=-1,-1,-1,-1,0)(370=-1,-1,-1,-1,0)(160=-1,-1,-1,-1,0)(280=-1,-1,-1,-1,0)(240=-1,-1,-1,-1,0)</Name>
|
||||||
|
</SetRegEntry>
|
||||||
|
<SetRegEntry>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Key>ARMDBGFLAGS</Key>
|
||||||
|
<Name>-T0</Name>
|
||||||
|
</SetRegEntry>
|
||||||
|
<SetRegEntry>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Key>UL2CM3</Key>
|
||||||
|
<Name>-O463 -S0 -C0 -FO7 -FD10000000 -FC800 -FN1 -FF0LPC_IAP_512 -FS00 -FL080000)</Name>
|
||||||
|
</SetRegEntry>
|
||||||
|
</TargetDriverDllRegistry>
|
||||||
|
<Breakpoint>
|
||||||
|
<Bp>
|
||||||
|
<Number>0</Number>
|
||||||
|
<Type>0</Type>
|
||||||
|
<LineNumber>11</LineNumber>
|
||||||
|
<EnabledFlag>1</EnabledFlag>
|
||||||
|
<Address>0</Address>
|
||||||
|
<ByteObject>0</ByteObject>
|
||||||
|
<HtxType>0</HtxType>
|
||||||
|
<ManyObjects>0</ManyObjects>
|
||||||
|
<SizeOfObject>0</SizeOfObject>
|
||||||
|
<BreakByAccess>0</BreakByAccess>
|
||||||
|
<BreakIfRCount>0</BreakIfRCount>
|
||||||
|
<Filename>F:\230953344\ES\Lab1\DATATRANSFER.asm</Filename>
|
||||||
|
<ExecCommand></ExecCommand>
|
||||||
|
<Expression></Expression>
|
||||||
|
</Bp>
|
||||||
|
</Breakpoint>
|
||||||
|
<MemoryWindow1>
|
||||||
|
<Mm>
|
||||||
|
<WinNumber>1</WinNumber>
|
||||||
|
<SubType>0</SubType>
|
||||||
|
<ItemText>0x000000A</ItemText>
|
||||||
|
</Mm>
|
||||||
|
</MemoryWindow1>
|
||||||
|
<DebugFlag>
|
||||||
|
<trace>0</trace>
|
||||||
|
<periodic>1</periodic>
|
||||||
|
<aLwin>1</aLwin>
|
||||||
|
<aCover>0</aCover>
|
||||||
|
<aSer1>0</aSer1>
|
||||||
|
<aSer2>0</aSer2>
|
||||||
|
<aPa>0</aPa>
|
||||||
|
<viewmode>1</viewmode>
|
||||||
|
<vrSel>0</vrSel>
|
||||||
|
<aSym>0</aSym>
|
||||||
|
<aTbox>0</aTbox>
|
||||||
|
<AscS1>0</AscS1>
|
||||||
|
<AscS2>0</AscS2>
|
||||||
|
<AscS3>0</AscS3>
|
||||||
|
<aSer3>0</aSer3>
|
||||||
|
<eProf>0</eProf>
|
||||||
|
<aLa>0</aLa>
|
||||||
|
<aPa1>0</aPa1>
|
||||||
|
<AscS4>0</AscS4>
|
||||||
|
<aSer4>0</aSer4>
|
||||||
|
<StkLoc>0</StkLoc>
|
||||||
|
<TrcWin>0</TrcWin>
|
||||||
|
<newCpu>0</newCpu>
|
||||||
|
<uProt>0</uProt>
|
||||||
|
</DebugFlag>
|
||||||
|
<Tracepoint>
|
||||||
|
<THDelay>0</THDelay>
|
||||||
|
</Tracepoint>
|
||||||
|
<LintExecutable></LintExecutable>
|
||||||
|
<LintConfigFile></LintConfigFile>
|
||||||
|
</TargetOption>
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
<Group>
|
||||||
|
<GroupName>Source Group 1</GroupName>
|
||||||
|
<tvExp>1</tvExp>
|
||||||
|
<tvExpOptDlg>0</tvExpOptDlg>
|
||||||
|
<cbSel>0</cbSel>
|
||||||
|
<RteFlg>0</RteFlg>
|
||||||
|
<File>
|
||||||
|
<GroupNumber>1</GroupNumber>
|
||||||
|
<FileNumber>1</FileNumber>
|
||||||
|
<FileType>2</FileType>
|
||||||
|
<tvExp>0</tvExp>
|
||||||
|
<Focus>0</Focus>
|
||||||
|
<ColumnNumber>25</ColumnNumber>
|
||||||
|
<tvExpOptDlg>0</tvExpOptDlg>
|
||||||
|
<TopLine>1</TopLine>
|
||||||
|
<CurrentLine>5</CurrentLine>
|
||||||
|
<bDave2>0</bDave2>
|
||||||
|
<PathWithFileName>.\DATATRANSFER.asm</PathWithFileName>
|
||||||
|
<FilenameWithoutPath>DATATRANSFER.asm</FilenameWithoutPath>
|
||||||
|
<RteFlg>0</RteFlg>
|
||||||
|
<bShared>0</bShared>
|
||||||
|
</File>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
</ProjectOpt>
|
BIN
ES/Lab/Lab1/Init/init_uvproj.bak
Normal file
BIN
ES/Lab/Lab1/Init/init_uvproj.bak
Normal file
Binary file not shown.
60
ES/Lab/Lab1/Init2/DATATRANSFER.asm
Normal file
60
ES/Lab/Lab1/Init2/DATATRANSFER.asm
Normal file
|
@ -0,0 +1,60 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; DATATRANSFER.asm - Memory-Based Data Transfer Operations Demonstration
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates how to transfer data from memory locations to registers
|
||||||
|
; using ARM load instructions. It shows the difference between loading an address
|
||||||
|
; and loading the actual data stored at that address.
|
||||||
|
|
||||||
|
AREA RESET,DATA,READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA mycode,CODE,READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; This function demonstrates memory data transfer operations:
|
||||||
|
; 1. Load the address of a data array into a register
|
||||||
|
; 2. Load the actual data from that memory location
|
||||||
|
; 3. Load an immediate negative value for comparison
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Load memory address into register
|
||||||
|
; LDR with = syntax loads the address of the SRC array into R0
|
||||||
|
; This gives us a pointer to the beginning of the data array
|
||||||
|
LDR R0, =SRC ; R0 = address of SRC array
|
||||||
|
|
||||||
|
; Step 2: Load data from memory location
|
||||||
|
; LDR with [] syntax loads the actual data stored at the address in R0
|
||||||
|
; This reads the first 32-bit word from the SRC array (0x12345678)
|
||||||
|
LDR R1, [R0] ; R1 = data at address in R0 (first element of SRC)
|
||||||
|
|
||||||
|
; Step 3: Load immediate negative value
|
||||||
|
; MOV instruction loads the immediate negative value -8 into R5
|
||||||
|
; This demonstrates mixing memory loads with immediate loads
|
||||||
|
MOV R5, -8 ; R5 = -8 (immediate negative value)
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
; Create an infinite loop to stop program execution
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Source data array
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC array contains three 32-bit words in hexadecimal format:
|
||||||
|
; - First word: 0x12345678 (305419896 in decimal)
|
||||||
|
; - Second word: 0xABCDEF55 (2882400341 in decimal)
|
||||||
|
; - Third word: 0x55 (85 in decimal)
|
||||||
|
SRC DCD 0x12345678, 0xABCDEF55, 0x55
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
||||||
|
|
1
ES/Lab/Lab1/Init2/description.md
Normal file
1
ES/Lab/Lab1/Init2/description.md
Normal file
|
@ -0,0 +1 @@
|
||||||
|
LDR and SRC array
|
85
ES/Lab/Lab2/array_reversal.asm
Normal file
85
ES/Lab/Lab2/array_reversal.asm
Normal file
|
@ -0,0 +1,85 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; array_reversal.asm - Array Reversal Using Swap Algorithm
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates how to reverse an array in-place using a swap algorithm.
|
||||||
|
; The algorithm uses two pointers - one starting from the beginning and one from the end
|
||||||
|
; of the array. Elements are swapped in each iteration, and the pointers move towards
|
||||||
|
; the center until they meet or cross each other.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA mycode,CODE,READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Initialize counter R2 to half the array size (5 iterations for 10 elements)
|
||||||
|
; 2. Set R0 to point to the start of the array (SRC)
|
||||||
|
; 3. Set R1 to point to the end of the array (SRC + 36 bytes = last element)
|
||||||
|
; 4. In each iteration:
|
||||||
|
; a. Load element from start pointer (R0) into R3
|
||||||
|
; b. Load element from end pointer (R1) into R4
|
||||||
|
; c. Store R3 to end pointer location and decrement R1 by 4 bytes
|
||||||
|
; d. Store R4 to start pointer location and increment R0 by 4 bytes
|
||||||
|
; e. Decrement counter and repeat until counter reaches zero
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize loop counter
|
||||||
|
; Set R2 to 5 (half of array size 10) - number of swap operations needed
|
||||||
|
MOV R2, #5 ; R2 = 5 (loop counter for 5 swap operations)
|
||||||
|
|
||||||
|
; Step 2: Initialize array pointers
|
||||||
|
; R0 points to the beginning of the array
|
||||||
|
LDR R0, =SRC ; R0 = address of first element in SRC array
|
||||||
|
|
||||||
|
; R1 points to the end of the array (SRC + 36 bytes)
|
||||||
|
; 36 = 9 * 4 bytes (offset to reach the last element from first)
|
||||||
|
LDR R1, =SRC + 36 ; R1 = address of last element in SRC array
|
||||||
|
|
||||||
|
; Step 3: Main reversal loop
|
||||||
|
Loop
|
||||||
|
; Load the element from the start of array into R3
|
||||||
|
LDR R3, [R0] ; R3 = element at current start position
|
||||||
|
|
||||||
|
; Load the element from the end of array into R4
|
||||||
|
LDR R4, [R1] ; R4 = element at current end position
|
||||||
|
|
||||||
|
; Swap: Store start element (R3) to end position
|
||||||
|
; Use post-decrement addressing: store R3 to [R1], then R1 = R1 - 4
|
||||||
|
STR R3, [R1], #-4 ; Store R3 to end position and move pointer left
|
||||||
|
|
||||||
|
; Swap: Store end element (R4) to start position
|
||||||
|
; Use post-increment addressing: store R4 to [R0], then R0 = R0 + 4
|
||||||
|
STR R4, [R0], #4 ; Store R4 to start position and move pointer right
|
||||||
|
|
||||||
|
; Decrement loop counter
|
||||||
|
SUBS R2, #1 ; R2 = R2 - 1 (set flags for branch condition)
|
||||||
|
|
||||||
|
; Continue loop if counter is not zero
|
||||||
|
BNE Loop ; Branch to Loop if R2 != 0
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
; Create an infinite loop to stop program execution
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
AREA mydate, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Source Array
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC array contains 10 elements (40 bytes total):
|
||||||
|
; Each element is a 32-bit word in hexadecimal format
|
||||||
|
; Original array: [32, 12345644, 05, 98, AB, CD, 55, 32, CA, 45]
|
||||||
|
; After reversal: [45, CA, 32, 55, CD, AB, 98, 05, 12345644, 32]
|
||||||
|
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
79
ES/Lab/Lab2/swap/LOOP.asm
Normal file
79
ES/Lab/Lab2/swap/LOOP.asm
Normal file
|
@ -0,0 +1,79 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; LOOP.asm - Efficient Array Copy Using Loop Construct
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates an efficient way to copy data from one array to another
|
||||||
|
; using a loop construct. This approach is much more scalable and maintainable
|
||||||
|
; compared to individual copy operations, especially for larger arrays.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA mycode,CODE,READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Initialize array pointers (R0 = SRC address, R1 = DST address)
|
||||||
|
; 2. Set loop counter R2 to the number of elements to copy (10)
|
||||||
|
; 3. In each iteration of the loop:
|
||||||
|
; a. Load element from SRC array using post-increment addressing
|
||||||
|
; b. Store element to DST array using post-increment addressing
|
||||||
|
; c. Decrement counter and check if more iterations are needed
|
||||||
|
; 4. This approach is much more efficient than individual operations for large arrays
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize array pointers
|
||||||
|
; R0 points to the beginning of the source array
|
||||||
|
LDR R0, =SRC ; R0 = address of first element in SRC array
|
||||||
|
|
||||||
|
; R1 points to the beginning of the destination array
|
||||||
|
LDR R1, =DST ; R1 = address of first element in DST array
|
||||||
|
|
||||||
|
; Step 2: Initialize loop counter
|
||||||
|
; R2 holds the number of elements to copy (10 elements total)
|
||||||
|
MOV R2,#10 ; R2 = 10 (number of elements to copy)
|
||||||
|
|
||||||
|
; Step 3: Main copy loop
|
||||||
|
BACK
|
||||||
|
; Load from SRC array and advance pointer
|
||||||
|
; LDR R3, [R0], #4 means: R3 = [R0], then R0 = R0 + 4
|
||||||
|
LDR R3,[R0],#4 ; Load next element from SRC and advance R0
|
||||||
|
|
||||||
|
; Store to DST array and advance pointer
|
||||||
|
; STR R3, [R1], #4 means: [R1] = R3, then R1 = R1 + 4
|
||||||
|
STR R3,[R1],#04 ; Store element to DST and advance R1
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
SUBS R2,#1 ; R2 = R2 - 1 (set flags for branch condition)
|
||||||
|
|
||||||
|
; Branch back to BACK if R2 is not zero
|
||||||
|
BNE BACK ; If R2 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
; Create an infinite loop to stop program execution
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Source and Destination Arrays
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC array contains 10 elements (40 bytes total):
|
||||||
|
; Each element is a 32-bit word in hexadecimal format
|
||||||
|
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
|
||||||
|
|
||||||
|
AREA mydate, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; DST array - initially contains space for one element, but will be expanded
|
||||||
|
; during copy operations. The loop will copy all 10 elements from SRC to DST
|
||||||
|
DST DCD 0
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
83
ES/Lab/Lab2/swap/LOOP2.asm
Normal file
83
ES/Lab/Lab2/swap/LOOP2.asm
Normal file
|
@ -0,0 +1,83 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; LOOP2.asm - Array Copy Using Loop with Proper Destination Array Size
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates the same array copy algorithm as LOOP.asm but with
|
||||||
|
; two key improvements:
|
||||||
|
; 1. Uses R12 as the loop counter (R12 is typically used for intra-procedure calls)
|
||||||
|
; 2. Pre-allocates the correct size for the destination array (10 elements)
|
||||||
|
; This version is more complete and avoids potential memory issues.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA mycode,CODE,READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Initialize array pointers (R0 = SRC address, R1 = DST address)
|
||||||
|
; 2. Set loop counter R12 to the number of elements to copy (10)
|
||||||
|
; 3. In each iteration of the loop:
|
||||||
|
; a. Load element from SRC array using post-increment addressing
|
||||||
|
; b. Store element to DST array using post-increment addressing
|
||||||
|
; c. Decrement counter and check if more iterations are needed
|
||||||
|
; 4. This version properly allocates destination array space beforehand
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize array pointers
|
||||||
|
; R0 points to the beginning of the source array
|
||||||
|
LDR R0, =SRC ; R0 = address of first element in SRC array
|
||||||
|
|
||||||
|
; R1 points to the beginning of the destination array
|
||||||
|
LDR R1, =DST ; R1 = address of first element in DST array
|
||||||
|
|
||||||
|
; Step 2: Initialize loop counter
|
||||||
|
; R12 holds the number of elements to copy (10 elements total)
|
||||||
|
; Using R12 is a common convention for loop counters in ARM assembly
|
||||||
|
MOV R12, #10 ; R12 = 10 (number of elements to copy)
|
||||||
|
|
||||||
|
; Step 3: Main copy loop
|
||||||
|
Loop
|
||||||
|
; Load from SRC array and advance pointer
|
||||||
|
; LDR R2, [R0], #4 means: R2 = [R0], then R0 = R0 + 4
|
||||||
|
LDR R2, [R0], #4 ; Load next element from SRC and advance R0
|
||||||
|
|
||||||
|
; Store to DST array and advance pointer
|
||||||
|
; STR R2, [R1], #4 means: [R1] = R2, then R1 = R1 + 4
|
||||||
|
STR R2, [R1], #4 ; Store element to DST and advance R1
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
; SUBS R12, R12, #1 is equivalent to SUBS R12, #1
|
||||||
|
SUBS R12, R12, #1 ; R12 = R12 - 1 (set flags for branch condition)
|
||||||
|
|
||||||
|
; Branch back to Loop if R12 is not zero
|
||||||
|
BNE Loop ; If R12 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
; Create an infinite loop to stop program execution
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Source and Destination Arrays
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC array contains 10 elements (40 bytes total):
|
||||||
|
; Each element is a 32-bit word in hexadecimal format
|
||||||
|
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
|
||||||
|
|
||||||
|
AREA mydate, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; DST array - properly pre-allocated with 10 elements (all initialized to 0)
|
||||||
|
; This ensures there is enough space for all copied elements
|
||||||
|
DST DCD 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
99
ES/Lab/Lab2/swap/MULTINDEX.asm
Normal file
99
ES/Lab/Lab2/swap/MULTINDEX.asm
Normal file
|
@ -0,0 +1,99 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; MULTINDEX.asm - Mixed Addressing Modes for Array Copy Operations
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates different addressing modes used in ARM assembly for
|
||||||
|
; array operations. It intentionally mixes various approaches to show the
|
||||||
|
; different ways memory can be accessed and how pointers are managed.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA mycode,CODE,READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; This program demonstrates various addressing modes for copying array elements:
|
||||||
|
; 1. Basic load/store without pointer advancement
|
||||||
|
; 2. Post-increment addressing (! symbol) - pointer advances after operation
|
||||||
|
; 3. Pre-indexed addressing without (!) - pointer doesn't advance automatically
|
||||||
|
; 4. Mixed approaches to show flexibility in ARM assembly programming
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize array pointers
|
||||||
|
; R0 points to the beginning of the source array
|
||||||
|
LDR R0, =SRC ; R0 = address of first element in SRC array
|
||||||
|
|
||||||
|
; R1 points to the beginning of the destination array
|
||||||
|
LDR R1, =DST ; R1 = address of first element in DST array
|
||||||
|
|
||||||
|
; Step 2: Copy first element - Basic addressing (no pointer advancement)
|
||||||
|
; Load from [R0] and store to [R1] without changing pointer values
|
||||||
|
LDR R2,[R0] ; R2 = SRC[0] (R0 unchanged)
|
||||||
|
STR R2,[R1] ; DST[0] = R2 (R1 unchanged)
|
||||||
|
|
||||||
|
; Step 3: Copy next 3 elements - Post-increment addressing
|
||||||
|
; Using '!' symbol means pointer is updated after the operation
|
||||||
|
LDR R3,[R0,#4]! ; R3 = SRC[1], then R0 = R0 + 4
|
||||||
|
STR R3,[R1,#4]! ; DST[1] = R3, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R4,[R0,#4]! ; R4 = SRC[2], then R0 = R0 + 4
|
||||||
|
STR R4,[R1,#4]! ; DST[2] = R4, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R5,[R0,#4]! ; R5 = SRC[3], then R0 = R0 + 4
|
||||||
|
STR R5,[R1,#4]! ; DST[3] = R5, then R1 = R1 + 4
|
||||||
|
|
||||||
|
; Step 4: Copy next 3 elements - Pre-indexed addressing without advancement
|
||||||
|
; Without '!' symbol, pointers are not automatically updated
|
||||||
|
; Manual pointer advancement is needed (not shown here, which may be intentional)
|
||||||
|
LDR R6,[R0,#4] ; R6 = SRC[4] (R0 unchanged)
|
||||||
|
STR R6,[R1,#4] ; DST[4] = R6 (R1 unchanged)
|
||||||
|
|
||||||
|
LDR R7,[R0,#4] ; R7 = SRC[5] (R0 unchanged)
|
||||||
|
STR R7,[R1,#4] ; DST[5] = R7 (R1 unchanged)
|
||||||
|
|
||||||
|
LDR R8,[R0,#4] ; R8 = SRC[6] (R0 unchanged)
|
||||||
|
STR R8,[R1,#4] ; DST[6] = R8 (R1 unchanged)
|
||||||
|
|
||||||
|
; Step 5: Copy last 3 elements - Post-increment addressing again
|
||||||
|
; Switch back to post-increment mode for the final elements
|
||||||
|
LDR R9,[R0],#4 ; R9 = SRC[7], then R0 = R0 + 4
|
||||||
|
STR R9,[R1],#4 ; DST[7] = R9, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R10,[R0],#4 ; R10 = SRC[8], then R0 = R0 + 4
|
||||||
|
STR R10,[R1],#4 ; DST[8] = R10, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R11,[R0],#4 ; R11 = SRC[9], then R0 = R0 + 4
|
||||||
|
STR R11,[R1],#4 ; DST[9] = R11, then R1 = R1 + 4
|
||||||
|
|
||||||
|
; Step 6: Program termination
|
||||||
|
; Create an infinite loop to stop program execution
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Source and Destination Arrays
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC array contains 10 elements (40 bytes total):
|
||||||
|
; Each element is a 32-bit word in hexadecimal format
|
||||||
|
; Note: The middle section (elements 4-6) uses pre-indexed addressing without
|
||||||
|
; pointer advancement, which means the same memory locations are accessed
|
||||||
|
; multiple times. This demonstrates different addressing mode behaviors.
|
||||||
|
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
|
||||||
|
|
||||||
|
AREA mydate, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; DST array - initially contains space for one element, but will be expanded
|
||||||
|
; during copy operations to accommodate all 10 elements
|
||||||
|
DST DCD 0
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
93
ES/Lab/Lab2/swap/SWAP.asm
Normal file
93
ES/Lab/Lab2/swap/SWAP.asm
Normal file
|
@ -0,0 +1,93 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; SWAP.asm - Basic Array Copy Using Post-Increment Addressing
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates how to copy data from one array to another using
|
||||||
|
; post-increment addressing mode. Each load/store operation automatically
|
||||||
|
; advances the pointer to the next array element, eliminating the need for
|
||||||
|
; separate pointer arithmetic instructions.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA mycode,CODE,READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Load addresses of source (SRC) and destination (DST) arrays
|
||||||
|
; 2. Copy each element individually using post-increment addressing
|
||||||
|
; 3. The '!' symbol after the offset means post-increment addressing:
|
||||||
|
; - Load from [R0, #4]! means: load from R0+4, then R0 = R0 + 4
|
||||||
|
; - Store to [R1, #4]! means: store to R1+4, then R1 = R1 + 4
|
||||||
|
; 4. This approach copies 10 elements (using registers R2-R11)
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize array pointers
|
||||||
|
; R0 points to the beginning of the source array
|
||||||
|
LDR R0, =SRC ; R0 = address of first element in SRC array
|
||||||
|
|
||||||
|
; R1 points to the beginning of the destination array
|
||||||
|
LDR R1, =DST ; R1 = address of first element in DST array
|
||||||
|
|
||||||
|
; Step 2: Copy first element (no post-increment for initial load)
|
||||||
|
; Load from SRC[0] into R2, store to DST[0]
|
||||||
|
LDR R2, [R0] ; R2 = SRC[0] (no increment yet)
|
||||||
|
STR R2, [R1] ; DST[0] = R2 (no increment yet)
|
||||||
|
|
||||||
|
; Step 3: Copy remaining elements using post-increment addressing
|
||||||
|
; Each load/store pair advances both pointers by 4 bytes automatically
|
||||||
|
LDR R3, [R0,#4]! ; R3 = SRC[1], then R0 = R0 + 4
|
||||||
|
STR R3, [R1,#4]! ; DST[1] = R3, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R4, [R0,#4]! ; R4 = SRC[2], then R0 = R0 + 4
|
||||||
|
STR R4, [R1,#4]! ; DST[2] = R4, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R5, [R0,#4]! ; R5 = SRC[3], then R0 = R0 + 4
|
||||||
|
STR R5, [R1,#4]! ; DST[3] = R5, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R6, [R0,#4]! ; R6 = SRC[4], then R0 = R0 + 4
|
||||||
|
STR R6, [R1,#4]! ; DST[4] = R6, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R7, [R0,#4]! ; R7 = SRC[5], then R0 = R0 + 4
|
||||||
|
STR R7, [R1,#4]! ; DST[5] = R7, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R8, [R0,#4]! ; R8 = SRC[6], then R0 = R0 + 4
|
||||||
|
STR R8, [R1,#4]! ; DST[6] = R8, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R9, [R0,#4]! ; R9 = SRC[7], then R0 = R0 + 4
|
||||||
|
STR R9, [R1,#4]! ; DST[7] = R9, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R10, [R0,#4]! ; R10 = SRC[8], then R0 = R0 + 4
|
||||||
|
STR R10, [R1,#4]! ; DST[8] = R10, then R1 = R1 + 4
|
||||||
|
|
||||||
|
LDR R11, [R0,#4]! ; R11 = SRC[9], then R0 = R0 + 4
|
||||||
|
STR R11, [R1,#4]! ; DST[9] = R11, then R1 = R1 + 4
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
; Create an infinite loop to stop program execution
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Source and Destination Arrays
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC array contains 10 elements (40 bytes total):
|
||||||
|
; Each element is a 32-bit word in hexadecimal format
|
||||||
|
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
|
||||||
|
|
||||||
|
AREA mydate, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; DST array - initially contains one zero, but will be expanded during copy operations
|
||||||
|
; The actual size will be determined by how many elements are copied
|
||||||
|
DST DCD 0
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
83
ES/Lab/Lab3/ADDER.asm
Normal file
83
ES/Lab/Lab3/ADDER.asm
Normal file
|
@ -0,0 +1,83 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; ADDER.asm - Sum of Array Elements with Carry Handling
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates how to sum all elements of an array using ARM assembly.
|
||||||
|
; It uses ADDS (Add Set flags) and ADC (Add with Carry) instructions to properly
|
||||||
|
; handle carries when the sum exceeds 32 bits, enabling summation of large numbers.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Initialize pointer to the array of numbers to be summed
|
||||||
|
; 2. Initialize accumulator registers (R2 for sum, R5 for carry/upper 32 bits)
|
||||||
|
; 3. Process each element in the array using a loop
|
||||||
|
; 4. Use ADDS to add each element and set carry flag
|
||||||
|
; 5. Use ADC to add the carry to the upper 32 bits
|
||||||
|
; 6. Store the final 64-bit sum (lower 32 bits + upper 32 bits)
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize array pointer and loop counter
|
||||||
|
; R0 points to the beginning of the source array
|
||||||
|
LDR R0, =SRC ; R0 = address of first element in SRC array
|
||||||
|
|
||||||
|
; R3 holds the number of elements to sum (10 elements total)
|
||||||
|
MOV R3, #10 ; R3 = 10 (loop counter)
|
||||||
|
|
||||||
|
; Step 2: Main summation loop
|
||||||
|
UP
|
||||||
|
; Load the next element from the array
|
||||||
|
; Post-increment addressing advances R0 to the next element
|
||||||
|
LDR R1, [R0], #4 ; Load next element into R1, advance R0
|
||||||
|
|
||||||
|
; Add the current element to the running sum
|
||||||
|
; ADDS adds R1 to R2 and sets condition flags including carry flag
|
||||||
|
; This handles addition within the lower 32 bits
|
||||||
|
ADDS R2, R1 ; R2 = R2 + R1, set carry flag if overflow
|
||||||
|
|
||||||
|
; Add the carry from the previous addition to the upper 32 bits
|
||||||
|
; ADC adds #0 + carry flag to R5, effectively capturing the carry
|
||||||
|
; This extends the summation to 64 bits total
|
||||||
|
ADC R5, #0 ; R5 = R5 + 0 + carry (from previous ADDS)
|
||||||
|
|
||||||
|
; Decrement loop counter and set condition flags
|
||||||
|
SUBS R3, #1 ; R3 = R3 - 1, set flags for branch condition
|
||||||
|
|
||||||
|
; Branch back to UP if counter is not zero
|
||||||
|
BNE UP ; If R3 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 3: Store the final result
|
||||||
|
; The result is a 64-bit sum stored in two 32-bit words
|
||||||
|
; R2 contains the lower 32 bits of the sum
|
||||||
|
; R5 contains the upper 32 bits (carry accumulated from all additions)
|
||||||
|
LDR R4, =Result ; R4 = address of result storage
|
||||||
|
STR R2, [R4] ; Store lower 32 bits of sum
|
||||||
|
STR R5, [R4] ; Store upper 32 bits (should be [R4, #4])
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - Array of numbers to be summed
|
||||||
|
; ========================================================================================
|
||||||
|
; SRC array contains 10 elements to be added together:
|
||||||
|
; Sum = 0x12345678 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
|
||||||
|
; The result will be stored as a 64-bit value due to potential overflow
|
||||||
|
SRC DCD 0x12345678, 0x00000001, 0x00000002, 0x00000003, 0x00000004, 0x00000005, 0x00000006, 0x00000007, 0x00000008, 0x00000009
|
||||||
|
|
||||||
|
AREA mydata, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; Result storage for the 64-bit sum
|
||||||
|
; Should store two 32-bit words: [lower_sum, upper_sum]
|
||||||
|
Result
|
||||||
|
DCD 0 ; Space for lower 32 bits of sum
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
96
ES/Lab/Lab3/add128bit.asm
Normal file
96
ES/Lab/Lab3/add128bit.asm
Normal file
|
@ -0,0 +1,96 @@
|
||||||
|
; ========================================================================================
|
||||||
|
; add128bit.asm - 128-Bit Addition Using Multiple Precision Arithmetic
|
||||||
|
; ========================================================================================
|
||||||
|
; This program demonstrates how to add two 128-bit numbers using ARM assembly.
|
||||||
|
; Since ARM registers are 32-bit, large numbers are stored as arrays of 32-bit words.
|
||||||
|
; The program uses ADCS (Add with Carry Set) instruction to handle carries between
|
||||||
|
; individual 32-bit words, enabling multi-precision arithmetic.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY ; Define a read-only data section for the vector table
|
||||||
|
EXPORT __Vectors ; Export the vector table for external linking
|
||||||
|
|
||||||
|
__Vectors ; Start of the vector table
|
||||||
|
DCD 0x10001000 ; Stack pointer initial value (points to top of stack)
|
||||||
|
DCD Reset_Handler ; Address of the reset handler (program entry point)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for the next section
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY ; Define the code section as read-only
|
||||||
|
ENTRY ; Mark the entry point of the program
|
||||||
|
EXPORT Reset_Handler ; Export the reset handler function
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Reset_Handler - Main program execution
|
||||||
|
; ========================================================================================
|
||||||
|
; Algorithm Overview:
|
||||||
|
; 1. Initialize pointers to two 128-bit numbers (stored as 4x32-bit words each)
|
||||||
|
; 2. Process each 32-bit word from least significant to most significant
|
||||||
|
; 3. Use ADCS instruction to add corresponding words and propagate carry
|
||||||
|
; 4. Store the result (there are some issues in the original code with result storage)
|
||||||
|
Reset_Handler
|
||||||
|
; Step 1: Initialize pointers to the two 128-bit numbers
|
||||||
|
; Each number is stored as an array of four 32-bit words
|
||||||
|
; N1 and N2 represent the two 128-bit operands
|
||||||
|
LDR R1, =N1 ; R1 = address of first 128-bit number (N1)
|
||||||
|
LDR R2, =N2 ; R2 = address of second 128-bit number (N2)
|
||||||
|
|
||||||
|
; Initialize loop counter for 4 iterations (4 words = 128 bits)
|
||||||
|
MOV R3, #4 ; R3 = 4 (number of 32-bit words to process)
|
||||||
|
|
||||||
|
; Step 2: Main addition loop - process each 32-bit word
|
||||||
|
UP
|
||||||
|
; Load the next 32-bit word from each operand
|
||||||
|
; Post-increment addressing advances pointers to next word
|
||||||
|
LDR R4, [R1], #4 ; Load word from N1, advance R1 to next word
|
||||||
|
LDR R5, [R2], #4 ; Load word from N2, advance R2 to next word
|
||||||
|
|
||||||
|
; Add the two words with carry from previous addition
|
||||||
|
; ADCS adds R5 + R4 + carry flag and sets carry flag for next iteration
|
||||||
|
; This handles carries between 32-bit word boundaries
|
||||||
|
ADCS R6, R5, R4 ; R6 = R5 + R4 + carry, set carry for next iteration
|
||||||
|
|
||||||
|
; Decrement loop counter
|
||||||
|
SUB R3, #1 ; R3 = R3 - 1
|
||||||
|
|
||||||
|
; Test if loop counter equals zero
|
||||||
|
; TEQ (Test Equal) compares R3 with #0 and sets condition flags
|
||||||
|
TEQ R3, #0 ; Set Z flag if R3 == 0
|
||||||
|
|
||||||
|
; Branch back to UP if counter is not zero (Z flag not set)
|
||||||
|
BNE UP ; If R3 != 0, continue loop
|
||||||
|
|
||||||
|
; Step 3: Store the result
|
||||||
|
; Note: There are issues in the original code here
|
||||||
|
; R2 has been incremented and no longer points to N2
|
||||||
|
; R5 contains the last loaded word, not part of the result
|
||||||
|
; R6 contains the last addition result but only the final word is stored
|
||||||
|
LDR R8, =Result ; R8 = address of result storage
|
||||||
|
STR R2, [R8], #4 ; Store incorrect value (should be R6)
|
||||||
|
STR R5, [R8] ; Store incorrect value (should be carry or next word)
|
||||||
|
|
||||||
|
; Step 4: Program termination
|
||||||
|
STOP
|
||||||
|
B STOP ; Branch to STOP label (infinite loop)
|
||||||
|
|
||||||
|
ALIGN ; Ensure proper alignment for data section
|
||||||
|
|
||||||
|
; ========================================================================================
|
||||||
|
; Data Section - 128-bit operands
|
||||||
|
; ========================================================================================
|
||||||
|
; N1: First 128-bit number stored as four 32-bit words (MSB to LSB):
|
||||||
|
; Word 0: 0x10002000, Word 1: 0x30004000, Word 2: 0x50006000, Word 3: 0x70008000
|
||||||
|
; Represents: 0x10002000300040005000600070008000 in hexadecimal
|
||||||
|
N1 DCD 0x10002000, 0x30004000, 0x50006000, 0x70008000
|
||||||
|
|
||||||
|
; N2: Second 128-bit number (same value as N1 for demonstration)
|
||||||
|
; Represents: 0x10002000300040005000600070008000 in hexadecimal
|
||||||
|
N2 DCD 0x10002000, 0x30004000, 0x50006000, 0x70008000
|
||||||
|
|
||||||
|
AREA mydata, DATA, READWRITE ; Define a read-write data section
|
||||||
|
|
||||||
|
; Result storage for the 128-bit sum
|
||||||
|
; Note: Should store 5 words (4 for result + 1 for final carry)
|
||||||
|
; Current allocation is insufficient for proper 128-bit result
|
||||||
|
Result DCD 0
|
||||||
|
|
||||||
|
END ; End of the assembly program
|
17
ES/Lab/Lab7/BinaryUP_PIN.c
Normal file
17
ES/Lab/Lab7/BinaryUP_PIN.c
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
// Question - WAP in EC to display 8 bit UP counter on the port pin 0.4 to 0.11
|
||||||
|
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
unsigned char x = 0;
|
||||||
|
int i = 0;
|
||||||
|
|
||||||
|
LPC_PINCON -> PINSEL0 = 0x0000<<8 ;
|
||||||
|
LPC_GPIO0 -> FIODIR = 0xFF<<4;
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
LPC_GPIO0 -> FIOPIN = x << 4;
|
||||||
|
x = (x+1)%256;
|
||||||
|
for(i = 0; i < 50000; i++);
|
||||||
|
}
|
||||||
|
}
|
21
ES/Lab/Lab7/SwitchCounter.c
Normal file
21
ES/Lab/Lab7/SwitchCounter.c
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
// Question - Connect a key on P1.23 and LEDs on P0.4-0.11. WAP in EC to display the number of times the PUSH to OFF switch is pressed on LEDs.
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
unsigned long x, count = 0;
|
||||||
|
|
||||||
|
LPC_PINCON -> PINSEL0 = 0x0000<<8 ; // LED
|
||||||
|
LPC_PINCON -> PINSEL3 = 0; // SWITCH
|
||||||
|
|
||||||
|
LPC_GPIO0 -> FIODIR = 0xFF<<4; // LED
|
||||||
|
LPC_GPIO1 -> FIODIR = 0 << 23; // SWITCH
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
x = LPC_GPIO1 -> FIOPIN & 1 << 23; // Initial value to refer to
|
||||||
|
if(!x){
|
||||||
|
count = (count + 1)%255; // Counter
|
||||||
|
LPC_GPIO0 -> FIOPIN = count << 4; // Modifying FIOPIN value to match count
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
24
ES/Lab/Lab7/SwitchUPDOWN.c
Normal file
24
ES/Lab/Lab7/SwitchUPDOWN.c
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
// Question - Connect a key on P1.23 and LEDs on P0.4-0.11. WAP in EC to display the number of times the PUSH to OFF switch is pressed on LEDs. Alternatively, when it is not pressed, it should be a down counter.
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
unsigned long x;
|
||||||
|
unsigned char count = 0;
|
||||||
|
|
||||||
|
LPC_PINCON -> PINSEL0 = 0x0000<<8 ; // LED
|
||||||
|
LPC_PINCON -> PINSEL3 = 0; // SWITCH
|
||||||
|
|
||||||
|
LPC_GPIO0 -> FIODIR = 0xFF<<4; // LED
|
||||||
|
LPC_GPIO1 -> FIODIR = 0 << 23; // SWITCH
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
x = LPC_GPIO1 -> FIOPIN & 1 << 23; // Initial value to refer to
|
||||||
|
if(!x){
|
||||||
|
count = (count + 1); // Counter
|
||||||
|
LPC_GPIO0 -> FIOPIN = count << 4; // Modifying FIOPIN value to match count
|
||||||
|
} else {
|
||||||
|
count = (count - 1); // Counter
|
||||||
|
LPC_GPIO0 -> FIOPIN = count << 4; // Modifying FIOPIN value to match count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
45
ES/Lab/Lab8/JOHNSON_Up_Down_Same_GPIO.c
Normal file
45
ES/Lab/Lab8/JOHNSON_Up_Down_Same_GPIO.c
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
unsigned long x, y, i, j;
|
||||||
|
|
||||||
|
// LEDs
|
||||||
|
LPC_PINCON->PINSEL0 = 0;
|
||||||
|
LPC_GPIO0->FIODIR = 0xFF<<15 | 0x0<<10;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
x = LPC_GPIO0->FIOPIN & (1 << 10);
|
||||||
|
if(x){
|
||||||
|
y = 1<<22;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOSET=y;
|
||||||
|
y = y>>1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
y = 1<<22;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOCLR=y;
|
||||||
|
y>>=1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!x){
|
||||||
|
y = 1<<15;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOSET=y;
|
||||||
|
y = y<<1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
y = 1<<15;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOCLR=y;
|
||||||
|
y = y<<1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
45
ES/Lab/Lab8/JOHNSON_Up_Down_Separate_GPIO.c
Normal file
45
ES/Lab/Lab8/JOHNSON_Up_Down_Separate_GPIO.c
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
#include <LPC17xx.h>
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
unsigned long x, y, i, j;
|
||||||
|
|
||||||
|
// LEDs
|
||||||
|
LPC_PINCON->PINSEL0 = 0;
|
||||||
|
LPC_GPIO0->FIODIR = 0xFF<<15;
|
||||||
|
|
||||||
|
LPC_GPIO2->FIODIR = 0x0<<12;
|
||||||
|
|
||||||
|
while(1){
|
||||||
|
x = LPC_GPIO2->FIOPIN & (1 << 12);
|
||||||
|
if(x){
|
||||||
|
y = 1<<22;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOSET=y;
|
||||||
|
y = y>>1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
y = 1<<22;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOCLR=y;
|
||||||
|
y>>=1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!x){
|
||||||
|
y = 1<<15;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOSET=y;
|
||||||
|
y = y<<1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
y = 1<<15;
|
||||||
|
for(i=0;i<8;i++){
|
||||||
|
LPC_GPIO0->FIOCLR=y;
|
||||||
|
y = y<<1;
|
||||||
|
for(j=0; j<800000; j++);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
72
ES/Lab/LabMidsem/PerfectPerf.asm
Normal file
72
ES/Lab/LabMidsem/PerfectPerf.asm
Normal file
|
@ -0,0 +1,72 @@
|
||||||
|
; question - find all divisors of a number like 6, and store in data memory. find if number is perfect or not. if sum of divisors is the number itself, then perfect. if perfect, store FF next to divisor list, otherwise store 11
|
||||||
|
; this version includes branching and works properly.
|
||||||
|
|
||||||
|
AREA RESET, DATA, READONLY
|
||||||
|
EXPORT __Vectors
|
||||||
|
__Vectors
|
||||||
|
DCD 0x10001000
|
||||||
|
DCD Reset_Handler
|
||||||
|
ALIGN
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY
|
||||||
|
ENTRY
|
||||||
|
EXPORT Reset_Handler
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
LDR R0, =9
|
||||||
|
LDR R1, =0x10001000
|
||||||
|
BL DivisorsSum
|
||||||
|
MOV R2, R0
|
||||||
|
MOV R3, R1
|
||||||
|
LDR R4, =9
|
||||||
|
CMP R2, R4
|
||||||
|
BNE not_perfect
|
||||||
|
LDR R5, =0x000000FF
|
||||||
|
STR R5, [R3]
|
||||||
|
B STOP
|
||||||
|
not_perfect
|
||||||
|
LDR R5, =0x00000011
|
||||||
|
STR R5, [R3]
|
||||||
|
STOP
|
||||||
|
B STOP
|
||||||
|
|
||||||
|
DivisorsSum
|
||||||
|
PUSH{R4-R7, LR}
|
||||||
|
MOV R6, R0
|
||||||
|
MOV R7, R1
|
||||||
|
MOV R5, #0
|
||||||
|
LSRS R3, R6, #1
|
||||||
|
MOV R4, #1
|
||||||
|
div_loop
|
||||||
|
CMP R4, R3
|
||||||
|
BGT div_end
|
||||||
|
MOV R0, R6
|
||||||
|
MOV R1, R4
|
||||||
|
BL IsDivisible
|
||||||
|
CMP R0, #1
|
||||||
|
BNE div_skip
|
||||||
|
STR R4, [R7], #4
|
||||||
|
ADD R5, R5, R4
|
||||||
|
div_skip
|
||||||
|
ADD R4, R4, #1
|
||||||
|
B div_loop
|
||||||
|
div_end
|
||||||
|
MOV R0, R5
|
||||||
|
MOV R1, R7
|
||||||
|
POP{R4-R7, LR}
|
||||||
|
BX LR
|
||||||
|
|
||||||
|
IsDivisible
|
||||||
|
PUSH{LR}
|
||||||
|
MOV R2, R0
|
||||||
|
id_loop
|
||||||
|
SUBS R2, R2, R1
|
||||||
|
BPL id_loop
|
||||||
|
ADDS R2, R2, R1
|
||||||
|
MOV R0, #0
|
||||||
|
CMP R2, #0
|
||||||
|
MOVEQ R0, #1
|
||||||
|
POP{LR}
|
||||||
|
BX LR
|
||||||
|
|
||||||
|
END
|
51
ES/Lab/LabMidsem/PerfectWithoutBranch.asm
Normal file
51
ES/Lab/LabMidsem/PerfectWithoutBranch.asm
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
; find all divisors of a number like 6, and store in data memory. find if number is perfect or not. if sum of divisors is the number itself, then perfect. if perfect, store FF next to divisor list, otherwise store 11
|
||||||
|
AREA RESET, DATA, READONLY
|
||||||
|
EXPORT __Vectors
|
||||||
|
__Vectors
|
||||||
|
DCD 0x10001000
|
||||||
|
DCD Reset_Handler
|
||||||
|
ALIGN
|
||||||
|
|
||||||
|
AREA MYCODE, CODE, READONLY
|
||||||
|
ENTRY
|
||||||
|
EXPORT Reset_Handler
|
||||||
|
|
||||||
|
Reset_Handler
|
||||||
|
LDR R0, =10 ; value
|
||||||
|
MOV R1, #0 ; counter
|
||||||
|
LDR R12, =0x10001000 ; address
|
||||||
|
MOV R2, #1 ; factoriser
|
||||||
|
MOV R4, R0
|
||||||
|
LSRS R4, R4, #1
|
||||||
|
LOOP_I ; loop
|
||||||
|
CMP R2, R4
|
||||||
|
BHI DONE_LOOP
|
||||||
|
MOV R3, R0
|
||||||
|
DIV_LOOP ; division
|
||||||
|
CMP R3, R2
|
||||||
|
BLT CHECK_REM
|
||||||
|
SUB R3, R3, R2
|
||||||
|
B DIV_LOOP
|
||||||
|
CHECK_REM ; checks if factor
|
||||||
|
CMP R3, #0
|
||||||
|
BNE NEXT_I
|
||||||
|
ADD R1, R1, R2
|
||||||
|
STR R2, [R12]
|
||||||
|
ADD R12, R12, #4
|
||||||
|
NEXT_I ; iterator
|
||||||
|
ADD R2, R2, #1
|
||||||
|
B LOOP_I
|
||||||
|
DONE_LOOP ; checker for perfect
|
||||||
|
CMP R1, R0
|
||||||
|
BNE NOT_PERF
|
||||||
|
MOV R5, #0xFF
|
||||||
|
B STORE_FLAG
|
||||||
|
NOT_PERF
|
||||||
|
MOV R5, #0x11
|
||||||
|
STORE_FLAG ; store
|
||||||
|
STR R5, [R12]
|
||||||
|
STOP
|
||||||
|
B STOP
|
||||||
|
|
||||||
|
END
|
||||||
|
|
BIN
ES/Lab/Troubleshooting_ARM LPC 1768.pdf
Normal file
BIN
ES/Lab/Troubleshooting_ARM LPC 1768.pdf
Normal file
Binary file not shown.
58
ES/Lab/qui.md
Normal file
58
ES/Lab/qui.md
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
| Instruction | Description | Example | Effect / Notes |
|
||||||
|
|---|---|---:|---|
|
||||||
|
| MOV Rd, Rn | Move register → register | MOV R0, R1 | Copies value of R1 into R0 |
|
||||||
|
| MOV Rd, #imm | Move immediate value | MOV R0, #0x12 | Loads constant into Rd |
|
||||||
|
| MOVW Rd, #imm | Move lower 16 bits | MOVW R0, #0x1234 | Only lower 16 bits changed |
|
||||||
|
| MOVT Rd, #imm | Move upper 16 bits | MOVT R0, #0x1234 | Only upper 16 bits changed |
|
||||||
|
| MVN Rd, Rn | Move bitwise NOT | MVN R0, R1 | R0 = NOT R1 |
|
||||||
|
| LDR Rd, [Rn] | Load word | LDR R0, [R1] | R0 = 32-bit value from mem at R1 |
|
||||||
|
| STR Rd, [Rn] | Store word | STR R0, [R1] | Store R0 into mem at R1 |
|
||||||
|
| LDRB Rd, [Rn] | Load byte | LDRB R0, [R1] | Zero-extends 8-bit mem into Rd |
|
||||||
|
| STRB Rd, [Rn] | Store byte | STRB R0, [R1] | Stores only low byte of R0 |
|
||||||
|
| LDRH Rd, [Rn] | Load halfword | LDRH R0, [R1] | Zero-extends 16-bit mem into Rd |
|
||||||
|
| STRH Rd, [Rn] | Store halfword | STRH R0, [R1] | Stores only low halfword of R0 |
|
||||||
|
| LDRSB Rd, [Rn] | Load signed byte | LDRSB R0, [R1] | Sign-extends 8-bit mem into Rd |
|
||||||
|
| LDRSH Rd, [Rn] | Load signed halfword | LDRSH R0, [R1] | Sign-extends 16-bit mem into Rd |
|
||||||
|
| ADD Rd, Rn, Op2 | Add | ADD R0, R1, R2 | R0 = R1 + Op2 |
|
||||||
|
| ADC Rd, Rn, Op2 | Add with carry | ADC R0, R1, R2 | Adds carry flag C |
|
||||||
|
| ADDS Rd, Rn, Op2 | Add & set flags | ADDS R0, R1, R2 | Updates N, Z, C, V |
|
||||||
|
| ADCS Rd, Rn, Op2 | Add w/ carry & flags | ADCS R0, R1, R2 | Adds C & updates flags |
|
||||||
|
| SUB Rd, Rn, Op2 | Subtract | SUB R0, R1, R2 | R0 = R1 - Op2 |
|
||||||
|
| SBC Rd, Rn, Op2 | Subtract with carry | SBC R0, R1, R2 | R0 = R1 - Op2 - (1 - C) |
|
||||||
|
| RSB Rd, Rn, Op2 | Reverse subtract | RSB R0, R1, R2 | R0 = Op2 - R1 |
|
||||||
|
| RSC Rd, Rn, Op2 | Reverse sub w/ carry | RSC R0, R1, R2 | R0 = Op2 - R1 - (1 - C) |
|
||||||
|
| MUL Rd, Rn, Rm | Multiply | MUL R0, R1, R2 | R0 = R1 × R2 |
|
||||||
|
| MLA Rd, Rs1, Rs2, Rs3 | Multiply & accumulate | MLA R0, R1, R2, R3 | R0 = (Rs1 × Rs2) + Rs3 |
|
||||||
|
| MLS Rd, Rm, Rs, Rn | Multiply & subtract | MLS R0, R1, R2, R3 | R0 = Rn - (Rs × Rm) |
|
||||||
|
| UMULL RdLo, RdHi, Rn, Rm | Unsigned multiply long | UMULL R0, R1, R2, R3 | 64-bit result split across RdHi:RdLo |
|
||||||
|
| SMULL RdLo, RdHi, Rn, Rm | Signed multiply long | SMULL R0, R1, R2, R3 | Signed 64-bit result |
|
||||||
|
| AND Rd, Rn, Op2 | Bitwise AND | AND R0, R1, R2 | R0 = R1 AND Op2 |
|
||||||
|
| ORR Rd, Rn, Op2 | Bitwise OR | ORR R0, R1, R2 | R0 = R1 OR Op2 |
|
||||||
|
| ORN Rd, Rn, Op2 | Bitwise OR NOT | ORN R0, R1, R2 | R0 = R1 OR (NOT Op2) |
|
||||||
|
| EOR Rd, Rn, Op2 | Bitwise XOR | EOR R0, R1, R2 | R0 = R1 XOR Op2 |
|
||||||
|
| TST Rn, Op2 | Test bits (AND) | TST R0, #0x08 | Flags from Rn AND Op2 |
|
||||||
|
| TEQ Rn, Op2 | Test equivalence (XOR) | TEQ R0, R1 | Flags from Rn XOR Op2 |
|
||||||
|
| LSL Rd, Rn, Op2 | Logical shift left | LSL R0, R1, #2 | Shift left, fill with 0 |
|
||||||
|
| LSR Rd, Rn, Op2 | Logical shift right | LSR R0, R1, #2 | Shift right, fill with 0 |
|
||||||
|
| ASR Rd, Rn, Op2 | Arithmetic shift right | ASR R0, R1, #2 | Shift right, fill with sign bit |
|
||||||
|
| ROR Rd, Rn, Op2 | Rotate right | ROR R0, R1, #1 | Bits wrap around right |
|
||||||
|
| RRX Rd, Rm | Rotate right w/ extend | RRX R0, R1 | Rotate through carry |
|
||||||
|
| CMP Rn, Op2 | Compare (subtract) | CMP R0, #10 | Flags from Rn - Op2 |
|
||||||
|
| CMN Rn, Op2 | Compare negative | CMN R0, #5 | Flags from Rn + Op2 |
|
||||||
|
| B label | Branch | B loop | Unconditional jump |
|
||||||
|
| BL label | Branch w/ link | BL func | Calls function, LR = return addr |
|
||||||
|
| BX Rm | Branch indirect | BX LR | Jump to address in Rm |
|
||||||
|
| BEQ label | Branch if equal | BEQ done | Z = 1 |
|
||||||
|
| BNE label | Branch if not equal | BNE loop | Z = 0 |
|
||||||
|
| BCS label | Branch if carry set | BCS carry_case | C = 1 |
|
||||||
|
| BCC label | Branch if carry clear | BCC no_carry | C = 0 |
|
||||||
|
| BMI label | Branch if negative | BMI neg_case | N = 1 |
|
||||||
|
| BPL label | Branch if positive | BPL pos_case | N = 0 |
|
||||||
|
| BVS label | Branch if overflow set | BVS ovf_case | V = 1 |
|
||||||
|
| BVC label | Branch if overflow clear | BVC no_ovf | V = 0 |
|
||||||
|
| BLO label | Branch if lower (unsigned) | BLO lower_case | C = 0 & Z = 0 |
|
||||||
|
| BHS label | Branch if higher/same (unsigned) | BHS ok_case | C = 1 or Z = 1 |
|
||||||
|
| BGE label | Branch if ≥ (signed) | BGE greater_eq | V = N or Z = 1 |
|
||||||
|
| BLT label | Branch if < (signed) | BLT less_case | V ≠ N & Z = 0 |
|
||||||
|
| BGT label | Branch if > (signed) | BGT greater_case | V = N & Z = 0 |
|
||||||
|
| BLE label | Branch if ≤ (signed) | BLE less_eq | V ≠ N or Z = 1 |
|
156
IS/Lab/Eval/test.py
Normal file
156
IS/Lab/Eval/test.py
Normal file
|
@ -0,0 +1,156 @@
|
||||||
|
from functools import partial
|
||||||
|
import time
|
||||||
|
import numpy as np
|
||||||
|
import string
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
from Crypto.PublicKey import RSA
|
||||||
|
from Crypto.Cipher import AES, PKCS1_OAEP
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
from Crypto.Random import get_random_bytes
|
||||||
|
from sympy import Matrix # only for the 2×2 Hill inverse
|
||||||
|
|
||||||
|
|
||||||
|
# 1. Hill-Cipher utilities (2×2 matrix [[3,3],[2,5]])
|
||||||
|
|
||||||
|
hillkey = np.array([[3, 3],
|
||||||
|
[2, 5]], dtype=int)
|
||||||
|
ALPH = string.ascii_uppercase
|
||||||
|
m_len = 2 # block size
|
||||||
|
|
||||||
|
def clean(txt):
|
||||||
|
return ''.join(ch.upper() for ch in txt if ch.isalpha())
|
||||||
|
|
||||||
|
def hill_encrypt(pt, key=hillkey):
|
||||||
|
pt = clean(pt)
|
||||||
|
if len(pt) % m_len: # padding
|
||||||
|
pt += 'X' * (m_len - len(pt) % m_len)
|
||||||
|
cipher = []
|
||||||
|
for i in range(0, len(pt), m_len):
|
||||||
|
block = np.array([ALPH.index(ch) for ch in pt[i:i+m_len]])
|
||||||
|
cipher.extend((key @ block) % 26)
|
||||||
|
return ''.join(ALPH[i] for i in cipher)
|
||||||
|
|
||||||
|
def hill_decrypt(ct, key=hillkey):
|
||||||
|
# modular inverse of the matrix
|
||||||
|
M = Matrix(key)
|
||||||
|
detinv = pow(int(M.det()) % 26, -1, 26)
|
||||||
|
adj = M.adjugate()
|
||||||
|
inv_key = (detinv * adj) % 26
|
||||||
|
inv_key = np.array(inv_key).astype(int)
|
||||||
|
|
||||||
|
plain = []
|
||||||
|
for i in range(0, len(ct), m_len):
|
||||||
|
block = np.array([ALPH.index(ch) for ch in ct[i:i+m_len]])
|
||||||
|
plain.extend((inv_key @ block) % 26)
|
||||||
|
return ''.join(ALPH[i] for i in plain)
|
||||||
|
|
||||||
|
# Generic timing wrapper
|
||||||
|
def timed(fn, *a, **kw):
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
for _ in range(100_000): # 100 000 loops → 1 000 000 calls
|
||||||
|
fn(*a, **kw)
|
||||||
|
delta = time.perf_counter() - t0
|
||||||
|
return delta
|
||||||
|
|
||||||
|
# Menu
|
||||||
|
def menu():
|
||||||
|
while True:
|
||||||
|
print("\n===== Cryptographic Demo =====")
|
||||||
|
print("1. Hill-cipher demo")
|
||||||
|
print("2. RSA + envelope (share AES)")
|
||||||
|
print("3. AES-128 encrypt / decrypt")
|
||||||
|
print("4. Speed graph (100k it loops)")
|
||||||
|
print("0. Quit")
|
||||||
|
ch = input("Select >> ").strip()
|
||||||
|
if ch == '0': break
|
||||||
|
elif ch == '1': hill_demo()
|
||||||
|
elif ch == '2': rsa_env_demo()
|
||||||
|
elif ch == '3': aes_demo()
|
||||||
|
elif ch == '4': speed_graph()
|
||||||
|
else: print("Invalid choice")
|
||||||
|
|
||||||
|
# 1. Hill demo
|
||||||
|
def hill_demo():
|
||||||
|
msg = 'The key is hidden under the mattress'
|
||||||
|
print("\n------- 1. Hill-Cipher Demo -------")
|
||||||
|
print("Key matrix:\n", hillkey)
|
||||||
|
ct = hill_encrypt(msg)
|
||||||
|
print("Cipher :", ct)
|
||||||
|
pt = hill_decrypt(ct)
|
||||||
|
print("Plain :", pt) # uppercase / padded – expected
|
||||||
|
|
||||||
|
# 2. RSA Envelope demo
|
||||||
|
AES_KEY = b"0123456789ABCDEF" # 16-byte AES-128 key (truncated from prompt)
|
||||||
|
|
||||||
|
def rsa_env_demo():
|
||||||
|
print("\n------- 2. RSA × AES envelope Demo -------")
|
||||||
|
# generate RSA pairs
|
||||||
|
encoder_priv = RSA.generate(2048)
|
||||||
|
encoder_pub = encoder_priv.publickey()
|
||||||
|
|
||||||
|
decoder_priv = RSA.generate(2048) # strictly not needed, but shown
|
||||||
|
decoder_pub = decoder_priv.publickey()
|
||||||
|
|
||||||
|
# Use encoder_pub to encrypt the shared AES key
|
||||||
|
cipher_rsa = PKCS1_OAEP.new(encoder_pub)
|
||||||
|
enc_key = cipher_rsa.encrypt(AES_KEY)
|
||||||
|
|
||||||
|
# Show keys
|
||||||
|
print("Encoder public key (PEM):\n", encoder_pub.export_key().decode())
|
||||||
|
print("Encoder private key (PEM):\n", encoder_priv.export_key().decode())
|
||||||
|
print("Encrypted AES key (hex):", enc_key.hex())
|
||||||
|
|
||||||
|
# Decrypt back using encoder’s private key
|
||||||
|
dec_rsa = PKCS1_OAEP.new(encoder_priv)
|
||||||
|
dec_key = dec_rsa.decrypt(enc_key)
|
||||||
|
print("Decrypted AES key :", dec_key.hex(), " match=", dec_key==AES_KEY)
|
||||||
|
|
||||||
|
# 3. AES-128
|
||||||
|
def aes_demo():
|
||||||
|
msg = input("Enter AES plaintext:")
|
||||||
|
print("\n------- 3. AES-128 Demo -------")
|
||||||
|
cipher = AES.new(AES_KEY, AES.MODE_CBC) # random IV
|
||||||
|
ct = cipher.encrypt(pad(msg.encode(), AES.block_size))
|
||||||
|
print("Raw key :", AES_KEY.hex())
|
||||||
|
print("Ciphertext (incl. IV) :", cipher.iv.hex() + ct.hex())
|
||||||
|
decipher = AES.new(AES_KEY, AES.MODE_CBC, cipher.iv)
|
||||||
|
pt = unpad(decipher.decrypt(ct), AES.block_size).decode()
|
||||||
|
print("Recovered plaintext :", pt)
|
||||||
|
|
||||||
|
# 4. Speed test
|
||||||
|
def speed_graph():
|
||||||
|
print("\n------- Benchmark (100 000 loops = 1 Mio calls) -------")
|
||||||
|
# prepare one big dummy block for AES
|
||||||
|
aes_cipher = AES.new(AES_KEY, AES.MODE_ECB)
|
||||||
|
dummy_aes = b"A" * 16
|
||||||
|
|
||||||
|
# RSA encryption of AES key just once
|
||||||
|
pub_key = RSA.generate(2048).publickey()
|
||||||
|
rsa_cipher = PKCS1_OAEP.new(pub_key)
|
||||||
|
dummy_rsa = AES_KEY
|
||||||
|
|
||||||
|
# Hill needs string
|
||||||
|
hill_string = "HELLOWORLD"
|
||||||
|
hill_ct = hill_encrypt(hill_string) # pre-compute to keep test same
|
||||||
|
|
||||||
|
# timing
|
||||||
|
t_hill = timed(hill_encrypt, hill_string)
|
||||||
|
t_rsa = timed(rsa_cipher.encrypt, dummy_rsa)
|
||||||
|
t_aes = timed(aes_cipher.encrypt, dummy_aes)
|
||||||
|
|
||||||
|
methods = ['Hill-cipher\n(str encrypt)', 'RSA-OAEP\n(key wrap)', 'AES-128\n(block)']
|
||||||
|
timings = [t_hill, t_rsa, t_aes]
|
||||||
|
for name,val in zip(methods,timings):
|
||||||
|
print(f"{name:25s} : {val:9.4f} s (100 000 loops)")
|
||||||
|
|
||||||
|
plt.bar(methods, timings, color=['gold','coral','dodgerblue'])
|
||||||
|
plt.ylabel("Time (s) for 100 000 iterations")
|
||||||
|
plt.title("Relative speed among 3 algorithms")
|
||||||
|
plt.tight_layout()
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
##############################################################
|
||||||
|
# main
|
||||||
|
##############################################################
|
||||||
|
if __name__ == "__main__":
|
||||||
|
menu()
|
BIN
IS/Lab/ICT3141_ISLabManual.pdf
Normal file
BIN
IS/Lab/ICT3141_ISLabManual.pdf
Normal file
Binary file not shown.
54
IS/Lab/Lab0/Tools.md
Normal file
54
IS/Lab/Lab0/Tools.md
Normal file
|
@ -0,0 +1,54 @@
|
||||||
|
# Tool Exploration for Information Security
|
||||||
|
|
||||||
|
MS Teams Access Code: `hrtvl3x`
|
||||||
|
|
||||||
|
## [Kali Linux](https://www.kali.org/)
|
||||||
|
Kali Linux is a Debian based operating system maintained by the core Debian team to be used for cybersecurity applications specifically. While general OS installations limit certain hardware/software configurations for certain vectors of usage to prevent exploitation, Kali does no such thing - enabling the user to perform various kinds of operations with modularity. Kali is bundled with various readymade tools that allow automation of penetration testing in various stages. It is therefore used by penetration testing teams (both ethical and unethical) to carry out tests/exploits.
|
||||||
|
|
||||||
|
## [Owasp-Zap](https://www.zaproxy.org/)
|
||||||
|
Made by the Open Wroldwide Security Application Project (OWASP), Zed Attack Proxy (ZAP) is a web application vulnerability scanner designed for both automated and manual use. It acts a proxy server and inspects web traffic - analyzing network requests and related data for vulnerability exposure. It also has code review built in to assist fixing any possible issues before a piece of software is pushed into production.
|
||||||
|
|
||||||
|
## [Metasploit](https://www.metasploit.com/)
|
||||||
|
Designed to be a portable network tool in HD Moore in 2003, Metasploit has grown out to be an entire open source penetration testing framework, alongside its derivative sub projects like the OpCode Database, Shellcode Archive etc. Metasploit has, by itself, grown to be a collective of various tools throughout the decades, including coverage for most major publicly known exploits/CVEs used in the field - including those that were leaked from the NSA/TAO hacks in the late 2010s. It is a go to toolkit for penetration testers to approach security issues in any testing scenario.
|
||||||
|
|
||||||
|
## [Burpsuite](https://portswigger.net/burp)
|
||||||
|
BurpSuite is a tool focused at web exploitation, used by researchers reverse engineering products for APIs. It features detection and exploitation capabilities for vulnerabilities such as Cross Site Scripting (XSS), SQL Injection, Cross Site Request Forgery (CSRF), XML External Entity Injection, Server Side Request Forgery (SSRF) and more. It is used to exploit and map APIs from various applications as well, and can be then used to map them and perform any of the above mentioned exploits.
|
||||||
|
|
||||||
|
## [Ettercap](https://www.ettercap-project.org/)
|
||||||
|
Ettercap is a Man in the Middle (MITM) tool used by security researchers to ensure end to end security of data/action pipelines. It allows users to perform the following tests
|
||||||
|
- Host Lists through ARP requests sent to any subnet mask as specified by the user.
|
||||||
|
- Unified Sniffing: Kernel IP forwarding is disabled, user sends a request with a specific MAC address that is same as the attacker's one but with different IPs, so the packet is then return to the attacker instead.
|
||||||
|
- Bridged Sniffing
|
||||||
|
- ARP Poisoning
|
||||||
|
- ICMP redirection (Half Duplex MITM)
|
||||||
|
- DHCP Spoofing
|
||||||
|
- Port Stealing
|
||||||
|
- Character Injection
|
||||||
|
et cetera
|
||||||
|
|
||||||
|
## [Hydra](https://www.kali.org/tools/hydra/)
|
||||||
|
Hydra is a network login hacking tool built into Kali Linux used to gain unauthorized access to a remote system over various protocols and suites of tools, enabling an analyst to possibly establish/take down proxies, gain RCE, modify system resources (or their allocation and therefore cost). It supports SSL-based platforms as well and is easy to build extensions for to add support for a newer communication protocol.
|
||||||
|
|
||||||
|
## [Mosquitto](https://mosquitto.org/)
|
||||||
|
Mosquitto is an OSS MQTT broker designed for messaging/message passing applications, including message stores (to facilitate later delivery to a dormant user). It uses a PubSub model over TCP (which is a byeffect of its roots in MQTT) based on topics each client is subscribed to via JSON/XML. Mosquitto scanners are used to identify MQTT brokers during a communication stream and mapping them to engineer exploits accordingly.
|
||||||
|
|
||||||
|
## [nmap](https://nmap.org/)
|
||||||
|
NMap (Network Mapper) is a network discovery tool used in security auditing. NMap uses raw IP packets in various ways to map available hosts, services, versions, OSes, firewalls and can do so with scale and for large networks.
|
||||||
|
|
||||||
|
## [netcat](http://nmap.org/ncat/)
|
||||||
|
Netcat is used to read and write data across TCP/UDP connections via stdio and is a reliable backend tool to drive programs or scripts that require text passing usage. Ncat, its successor developed by the NMap team adds support for SSL, SOCK4/5 proxies, IPv6 support and other extended functionality. Due to its low level nature, it is easy to obscure and mask with ease.
|
||||||
|
|
||||||
|
## [sqlmap](https://sqlmap.org/)
|
||||||
|
sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It supports mosgt major database and database paradigms such as MySQL, PostgreSQL, Microsoft Access etc. It fully supports the following SQL injection techniques: boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries and out-of-band. It can connect via DBMS credentials if required, includes functionality to enumerate users, password hasehs, priveleges, roles, tables, columns etc.
|
||||||
|
|
||||||
|
## [sqlninja](https://www.kali.org/tools/sqlninja/)
|
||||||
|
SQLninja is a SQL server injection and takeover tool targeted to exploit SQL Injection vulnerabilities on a web application that uses Microsoft SQL Server as its back-end. Its main goal is to provide a remote access on the vulnerable DB server, even in a very hostile environment. It supports DB fingerprinting, dagta extraction, Metasploit integration to obtain a graphical access to the remote DB server through a VNC server injection or just to upload Meterpreter, obtain a DNS based or ICMP tunneled shell and bruteforcing of sa passwords too.
|
||||||
|
|
||||||
|
## [msfvenom](https://www.rapid7.com/blog/post/2011/05/24/introducing-msfvenom/)
|
||||||
|
MSFVenom is a fork off the Metasploit Framework merging both `msfpayload` and `msfencode` into one unified tool and framework instance, with a wider variety of I/O file formats and with refined payload generation.
|
||||||
|
|
||||||
|
## [Microsoft Threat Modelling Tool](https://learn.microsoft.com/en-us/azure/security/develop/threat-modeling-tool)
|
||||||
|
The Microsoft Threat Modeling Tool used as a part of the SDL allowing software architects to identify and mitigate any risks as they happen. It follows the STRIDE methodology: STRIDE stands for Spoofing, Tampering, Repudiation, Information disclosure, Denial of service and Elevation of privilege. A user designs their architecutre in STRIDE and marks the boundaries accordingly, and STRIDE gives us a list of all possible threat scenarios that the system could be exposed to by crossreferencing then Microsoft Security Database.
|
||||||
|
|
||||||
|
## [PyCharm](https://www.jetbrains.com/pycharm/)
|
||||||
|
PyCharm is the Jetbrains IDE for Python built for use in complex corporate workflows, with an entire extensive plugin ecosystem around it. It inlcudes PEP8 compliance checks, linters, treesitters etc to make development faster and more secure.
|
125
IS/Lab/Lab1/q1_monosub.py
Normal file
125
IS/Lab/Lab1/q1_monosub.py
Normal file
|
@ -0,0 +1,125 @@
|
||||||
|
## ptext = plaintext
|
||||||
|
## ctext = ciphertext
|
||||||
|
## mk = multiplicative key
|
||||||
|
## ak = additive key
|
||||||
|
|
||||||
|
def add_cipher_en(ptext, ak):
|
||||||
|
result = ""
|
||||||
|
for ch in ptext:
|
||||||
|
if ch.isalpha():
|
||||||
|
base = ord('A') if ch.isupper() else ord('a')
|
||||||
|
result += chr((ord(ch) - base + ak) % 26 + base)
|
||||||
|
else:
|
||||||
|
result += ch
|
||||||
|
return result
|
||||||
|
|
||||||
|
def add_cipher_de(ctext, ak):
|
||||||
|
result = ""
|
||||||
|
for ch in ctext:
|
||||||
|
if ch.isalpha():
|
||||||
|
base = ord('A') if ch.isupper() else ord('a')
|
||||||
|
result += chr((ord(ch) - base - ak) % 26 + base)
|
||||||
|
else:
|
||||||
|
result += ch
|
||||||
|
return result
|
||||||
|
|
||||||
|
def mult_cipher_en(ptext, mk):
|
||||||
|
result = ""
|
||||||
|
for ch in ptext:
|
||||||
|
if ch.isalpha():
|
||||||
|
base = ord('A') if ch.isupper() else ord('a')
|
||||||
|
x = ord(ch) - base
|
||||||
|
result += chr((x * mk) % 26 + base)
|
||||||
|
else:
|
||||||
|
result += ch
|
||||||
|
return result
|
||||||
|
|
||||||
|
def mult_cipher_de(ctext, mk):
|
||||||
|
result = ""
|
||||||
|
inverse = pow(mk, -1, 26)
|
||||||
|
for ch in ctext:
|
||||||
|
if ch.isalpha():
|
||||||
|
base = ord('A') if ch.isupper() else ord('a')
|
||||||
|
x = ord(ch) - base
|
||||||
|
result += chr((x * inverse) % 26 + base)
|
||||||
|
else:
|
||||||
|
result += ch
|
||||||
|
return result
|
||||||
|
|
||||||
|
def affine_en(ptext, ak, mk):
|
||||||
|
result = ""
|
||||||
|
for ch in ptext:
|
||||||
|
if ch.isalpha():
|
||||||
|
base = ord('A') if ch.isupper() else ord('a')
|
||||||
|
x = ord(ch) - base
|
||||||
|
result += chr(((x * mk + ak) % 26) + base)
|
||||||
|
else:
|
||||||
|
result += ch
|
||||||
|
return result
|
||||||
|
|
||||||
|
def affine_de(ctext, ak, mk):
|
||||||
|
result = ""
|
||||||
|
inverse = pow(mk, -1, 26)
|
||||||
|
for ch in ctext:
|
||||||
|
if ch.isalpha():
|
||||||
|
base = ord('A') if ch.isupper() else ord('a')
|
||||||
|
x = ord(ch) - base
|
||||||
|
result += chr((((x - ak) * inverse) % 26) + base)
|
||||||
|
else:
|
||||||
|
result += ch
|
||||||
|
return result
|
||||||
|
|
||||||
|
def mult_inverse(mk):
|
||||||
|
inverse = pow(mk, -1, 26)
|
||||||
|
return inverse
|
||||||
|
|
||||||
|
def operator(argument,ptext,ak,mk):
|
||||||
|
match argument:
|
||||||
|
case '1':
|
||||||
|
print("Additive Cipher")
|
||||||
|
print("Plaintext: ", ptext)
|
||||||
|
print("Additive Key: ", ak)
|
||||||
|
ctext = add_cipher_en(ptext, ak)
|
||||||
|
print("Ciphertext: ", ctext)
|
||||||
|
print("Decrypted Text: ", add_cipher_de(ctext, ak))
|
||||||
|
case '2':
|
||||||
|
print("Multiplicative Cipher")
|
||||||
|
print("Plaintext: ", ptext)
|
||||||
|
print("Multiplicative Key: ", mk)
|
||||||
|
ctext = mult_cipher_en(ptext, mk)
|
||||||
|
print("Ciphertext: ", ctext)
|
||||||
|
print("Multiplicative Inverse: ", mult_inverse(mk))
|
||||||
|
print("Decrypted Text: ", mult_cipher_de(ctext, mk))
|
||||||
|
case '3':
|
||||||
|
print("Affine Cipher")
|
||||||
|
print("Plaintext: ", ptext)
|
||||||
|
print("Additive Key: ", ak)
|
||||||
|
print("Multiplicative Key: ", mk)
|
||||||
|
ctext = affine_en(ptext, ak, mk)
|
||||||
|
print("Ciphertext: ", ctext)
|
||||||
|
print("Affine Inverse: ", mult_inverse(mk))
|
||||||
|
print("Decrypted Text: ", affine_de(ctext, ak, mk))
|
||||||
|
case '4':
|
||||||
|
print("Goodbye")
|
||||||
|
exit()
|
||||||
|
case _:
|
||||||
|
print("Invalid Choice, please try again.")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ptext = input("Kindly enter your desired plaintext: ")
|
||||||
|
ak = 20
|
||||||
|
mk = 15
|
||||||
|
|
||||||
|
print("Welcome to the substitution cipher system.")
|
||||||
|
print("Enter your choice of algorithm")
|
||||||
|
print("1. Additive Cipher")
|
||||||
|
print("2. Multiplicative Cipher")
|
||||||
|
print("3. Affine Cipher")
|
||||||
|
print("4. Exit")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
op = input("Enter your choice of operation: ")
|
||||||
|
operator(op, ptext, ak, mk)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
89
IS/Lab/Lab1/q2_autokey.py
Normal file
89
IS/Lab/Lab1/q2_autokey.py
Normal file
|
@ -0,0 +1,89 @@
|
||||||
|
def vigenere_en(ptext, vk):
|
||||||
|
result = []
|
||||||
|
ptext = ptext.upper()
|
||||||
|
vk = vk.upper()
|
||||||
|
kl = len(vk)
|
||||||
|
for i, ch in enumerate(ptext):
|
||||||
|
if ch.isalpha():
|
||||||
|
shift = (ord(vk[i % kl]) - ord('A')) % 26
|
||||||
|
result.append(chr((ord(ch) - ord('A') + shift) % 26 + ord('A')))
|
||||||
|
else:
|
||||||
|
result.append(ch)
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
|
||||||
|
def vigenere_de(ctext, vk):
|
||||||
|
result = []
|
||||||
|
ctext = ctext.upper()
|
||||||
|
vk = vk.upper()
|
||||||
|
kl = len(vk)
|
||||||
|
for i, ch in enumerate(ctext):
|
||||||
|
if ch.isalpha():
|
||||||
|
shift = (ord(vk[i % kl]) - ord('A')) % 26
|
||||||
|
result.append(chr((ord(ch) - ord('A') - shift) % 26 + ord('A')))
|
||||||
|
else:
|
||||||
|
result.append(ch)
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def autokey_en(ptext, ak):
|
||||||
|
k = ord(ak.upper()) if isinstance(ak, str) else ak
|
||||||
|
out = []
|
||||||
|
for ch in ptext.upper():
|
||||||
|
if ch.isalpha():
|
||||||
|
out_ch = chr((ord(ch) - 65 + (k - 65)) % 26 + 65)
|
||||||
|
out.append(out_ch); k = ord(ch)
|
||||||
|
else:
|
||||||
|
out.append(ch)
|
||||||
|
return ''.join(out)
|
||||||
|
|
||||||
|
def autokey_de(ctext, ak):
|
||||||
|
k = ord(ak.upper()) if isinstance(ak, str) else ak
|
||||||
|
out = []
|
||||||
|
for ch in ctext.upper():
|
||||||
|
if ch.isalpha():
|
||||||
|
p = chr((ord(ch) - 65 - (k - 65)) % 26 + 65)
|
||||||
|
out.append(p); k = ord(p)
|
||||||
|
else:
|
||||||
|
out.append(ch)
|
||||||
|
return ''.join(out)
|
||||||
|
|
||||||
|
def operator(argument,ptext,ak,vk):
|
||||||
|
match argument:
|
||||||
|
case '1':
|
||||||
|
print("Vigenere Cipher")
|
||||||
|
print("Plaintext: ", ptext)
|
||||||
|
print("Vigenere Key: ", vk)
|
||||||
|
ctext = vigenere_en(ptext, vk)
|
||||||
|
print("Ciphertext: ", ctext)
|
||||||
|
print("Decrypted Text: ", vigenere_de(ctext, vk))
|
||||||
|
case '2':
|
||||||
|
print("Autokey Cipher")
|
||||||
|
print("Plaintext: ", ptext)
|
||||||
|
print("Auto Key: ", ak)
|
||||||
|
ctext = autokey_en(ptext, ak)
|
||||||
|
print("Ciphertext: ", ctext)
|
||||||
|
print("Decrypted Text: ", autokey_de(ctext, ak))
|
||||||
|
case '3':
|
||||||
|
print("Goodbye")
|
||||||
|
exit()
|
||||||
|
case _:
|
||||||
|
print("Invalid Choice, please try again.")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ptext = input("Kindly enter your desired plaintext: ")
|
||||||
|
vk = input("Kindly enter the Vigenere Key: ")
|
||||||
|
ak = int(input("Kindly enter the Autokey: "))
|
||||||
|
|
||||||
|
print("Welcome to the Autokey cipher system.")
|
||||||
|
print("Enter your choice of algorithm")
|
||||||
|
print("1. Vigenere Cipher")
|
||||||
|
print("2. Autokey Cipher")
|
||||||
|
print("3. Exit")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
op = input("Enter your choice of operation: ")
|
||||||
|
operator(op, ptext, ak, vk)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
46
IS/Lab/Lab1/q3_playfair.py
Normal file
46
IS/Lab/Lab1/q3_playfair.py
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
def keymat(k):
|
||||||
|
k = k.upper().replace('J', 'I')
|
||||||
|
seen = set(); seq = []
|
||||||
|
for ch in (k + "ABCDEFGHIKLMNOPQRSTUVWXYZ"):
|
||||||
|
if ch.isalpha() and ch not in seen:
|
||||||
|
seen.add(ch); seq.append(ch)
|
||||||
|
return [seq[i:i+5] for i in range(0, 25, 5)]
|
||||||
|
|
||||||
|
def pairs(s, prep=True):
|
||||||
|
s = ''.join(ch for ch in s.upper() if ch.isalpha())
|
||||||
|
if prep:
|
||||||
|
s = s.replace('J', 'I')
|
||||||
|
p = []; i = 0
|
||||||
|
while i < len(s):
|
||||||
|
a = s[i]; b = s[i+1] if i+1 < len(s) else 'X'
|
||||||
|
if a == b:
|
||||||
|
p.append(a + 'X'); i += 1
|
||||||
|
else:
|
||||||
|
p.append(a + b); i += 2
|
||||||
|
return p
|
||||||
|
return [s[i:i+2] for i in range(0, len(s), 2)]
|
||||||
|
|
||||||
|
def playfair(text, key, enc=True):
|
||||||
|
m = keymat(key)
|
||||||
|
pos = {m[r][c]: (r, c) for r in range(5) for c in range(5)}
|
||||||
|
out = []
|
||||||
|
for a, b in pairs(text, prep=enc):
|
||||||
|
r1, c1 = pos[a]; r2, c2 = pos[b]
|
||||||
|
if r1 == r2:
|
||||||
|
out.append(m[r1][(c1 + (1 if enc else -1)) % 5] +
|
||||||
|
m[r2][(c2 + (1 if enc else -1)) % 5])
|
||||||
|
elif c1 == c2:
|
||||||
|
out.append(m[(r1 + (1 if enc else -1)) % 5][c1] +
|
||||||
|
m[(r2 + (1 if enc else -1)) % 5][c2])
|
||||||
|
else:
|
||||||
|
out.append(m[r1][c2] + m[r2][c1])
|
||||||
|
return ''.join(out)
|
||||||
|
|
||||||
|
enc = lambda pt, k: playfair(pt, k, True)
|
||||||
|
dec = lambda ct, k: playfair(ct, k, False)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
pt = input("Plaintext: ")
|
||||||
|
k = input("Key: ")
|
||||||
|
ct = enc(pt, k); print("Ciphertext:", ct)
|
||||||
|
print("Decrypted:", dec(ct, k))
|
54
IS/Lab/Lab1/q4_hill.py
Normal file
54
IS/Lab/Lab1/q4_hill.py
Normal file
|
@ -0,0 +1,54 @@
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
def hill_en(ptext, hk):
|
||||||
|
# keep only letters and convert to uppercase
|
||||||
|
ptext = ''.join(c.upper() for c in ptext if c.isalpha())
|
||||||
|
|
||||||
|
# matrix size
|
||||||
|
n = int(len(hk)**0.5)
|
||||||
|
|
||||||
|
# key matrix
|
||||||
|
key = np.array([ord(c) - 65 for c in hk]).reshape(n, n)
|
||||||
|
|
||||||
|
# padding
|
||||||
|
ptext += 'X' * (-len(ptext) % n)
|
||||||
|
|
||||||
|
# block operation
|
||||||
|
out_chars = []
|
||||||
|
for i in range(0, len(ptext), n):
|
||||||
|
block = np.array([ord(c) - 65 for c in ptext[i:i + n]])
|
||||||
|
encrypted_block = (key @ block) % 26
|
||||||
|
out_chars.extend(chr(int(val) + 65) for val in encrypted_block)
|
||||||
|
|
||||||
|
return ''.join(out_chars)
|
||||||
|
|
||||||
|
def hill_de(ctext, hk):
|
||||||
|
# keep only letters and convert to uppercase
|
||||||
|
ctext = ''.join(c.upper() for c in ctext if c.isalpha())
|
||||||
|
|
||||||
|
# matrix size
|
||||||
|
n = int(len(hk)**0.5)
|
||||||
|
|
||||||
|
# key matrix and its inverse (note: not a true modular inverse; kept minimal per lab)
|
||||||
|
key = np.array([ord(c) - 65 for c in hk]).reshape(n, n)
|
||||||
|
inv_key = np.linalg.inv(key)
|
||||||
|
inv_key = np.rint(inv_key).astype(int) % 26
|
||||||
|
|
||||||
|
# block operation
|
||||||
|
out_chars = []
|
||||||
|
for i in range(0, len(ctext), n):
|
||||||
|
block = np.array([ord(c) - 65 for c in ctext[i:i + n]])
|
||||||
|
decrypted_block = (inv_key @ block) % 26
|
||||||
|
out_chars.extend(chr(int(val) + 65) for val in decrypted_block)
|
||||||
|
|
||||||
|
return ''.join(out_chars)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ptext = input("Plaintext: ")
|
||||||
|
hk = input("Hill Key: ")
|
||||||
|
ctext = hill_en(ptext, hk)
|
||||||
|
print(f"Ciphertext: {ctext}")
|
||||||
|
print(f"Decrypted: {hill_de(ctext, hk)}")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
15
IS/Lab/Lab1/q5_john.py
Normal file
15
IS/Lab/Lab1/q5_john.py
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
from string import ascii_uppercase as A
|
||||||
|
|
||||||
|
def idx(c): return A.index(c)
|
||||||
|
def infer_shift(ct, pt):
|
||||||
|
return (idx(ct[0]) - idx(pt[0].upper())) % 26
|
||||||
|
|
||||||
|
def decrypt(ct, shift):
|
||||||
|
return ''.join(A[(idx(c) - shift) % 26] if c.isalpha() else c for c in ct)
|
||||||
|
|
||||||
|
known_ct = "CIW"
|
||||||
|
known_pt = "yes"
|
||||||
|
cipher = "XVIEWYWI"
|
||||||
|
|
||||||
|
shift = infer_shift(known_ct, known_pt)
|
||||||
|
print(decrypt(cipher, shift))
|
44
IS/Lab/Lab1/q6_affine_bf.py
Normal file
44
IS/Lab/Lab1/q6_affine_bf.py
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
def main():
|
||||||
|
# Affine cipher: E(x) = (ax + b) mod 26
|
||||||
|
# Given: "ab" -> "GL"
|
||||||
|
# a=0, b=1 -> G=6, L=11
|
||||||
|
|
||||||
|
ciphertext = "XPALASXYFGFUKPXUSOGEUTKCDGEXANMGNVS"
|
||||||
|
|
||||||
|
for a in range(1, 26):
|
||||||
|
if gcd(a, 26) != 1:
|
||||||
|
continue
|
||||||
|
a_inv = mod_inverse(a, 26)
|
||||||
|
if a_inv is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for b in range(26):
|
||||||
|
# check constraint: "ab" -> "GL" (a*0+b=6, a*1+b=11 mod 26)
|
||||||
|
if (b % 26 == 6) and ((a + b) % 26 == 11):
|
||||||
|
decrypted = []
|
||||||
|
for ch in ciphertext:
|
||||||
|
if ch.isalpha():
|
||||||
|
y = ord(ch.upper()) - ord('A')
|
||||||
|
x = (a_inv * (y - b)) % 26
|
||||||
|
decrypted.append(chr(x + ord('A')))
|
||||||
|
else:
|
||||||
|
decrypted.append(ch)
|
||||||
|
|
||||||
|
print(f"Key found: a={a}, b={b}")
|
||||||
|
print(f"Ciphertext: {ciphertext}")
|
||||||
|
print(f"Decrypted: {''.join(decrypted)}")
|
||||||
|
return
|
||||||
|
|
||||||
|
def gcd(a, b):
|
||||||
|
while b:
|
||||||
|
a, b = b, a % b
|
||||||
|
return a
|
||||||
|
|
||||||
|
def mod_inverse(a, m):
|
||||||
|
for i in range(1, m):
|
||||||
|
if (a * i) % m == 1:
|
||||||
|
return i
|
||||||
|
return None
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
31
IS/Lab/Lab2/3des.py
Normal file
31
IS/Lab/Lab2/3des.py
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
from Crypto.Cipher import DES3
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
|
||||||
|
def des3_cipher(key):
|
||||||
|
return DES3.new(key.encode('utf-8'), DES3.MODE_ECB)
|
||||||
|
|
||||||
|
def des3_en(ptext, key):
|
||||||
|
cipher = des3_cipher(key)
|
||||||
|
padded_text = pad(ptext.encode('utf-8'), DES3.block_size)
|
||||||
|
return cipher.encrypt(padded_text)
|
||||||
|
|
||||||
|
def des3_de(ctext, key):
|
||||||
|
cipher = des3_cipher(key)
|
||||||
|
decrypted = unpad(cipher.decrypt(ctext), DES3.block_size)
|
||||||
|
return decrypted.decode('utf-8')
|
||||||
|
|
||||||
|
def despad_key(key):
|
||||||
|
key = key.ljust(24)[:24]
|
||||||
|
return key
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Welcome to 3DES (Triple DES)")
|
||||||
|
ptext = input("Enter plaintext: ")
|
||||||
|
key = input("Enter key (minimum 16 characters for 3DES): ")
|
||||||
|
key = despad_key(key)
|
||||||
|
ctext = des3_en(ptext, key)
|
||||||
|
print("Your ciphertext: ", ctext)
|
||||||
|
print("Your decrypted plaintext: ", des3_de(ctext, key))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
34
IS/Lab/Lab2/aes_128.py
Normal file
34
IS/Lab/Lab2/aes_128.py
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
from Crypto.Cipher import AES
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
|
||||||
|
def aes_cipher(key):
|
||||||
|
return AES.new(key.encode('utf-8'), AES.MODE_ECB)
|
||||||
|
|
||||||
|
def aes_en(ptext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
ptext = pad(ptext.encode('utf-8'), AES.block_size)
|
||||||
|
return cipher.encrypt(ptext)
|
||||||
|
|
||||||
|
def aes_de(ctext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
decrypted = cipher.decrypt(ctext)
|
||||||
|
return unpad(decrypted, AES.block_size).decode('utf-8')
|
||||||
|
|
||||||
|
def aespad_key(key):
|
||||||
|
return key.ljust(16)[:16]
|
||||||
|
|
||||||
|
# 16 for 128 bit, 24 for 192, 32 for 256
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Welcome to AES-128")
|
||||||
|
ptext = input("Enter plaintext: ")
|
||||||
|
key = input("Enter key: ")
|
||||||
|
|
||||||
|
key = aespad_key(key)
|
||||||
|
|
||||||
|
ctext = aes_en(ptext, key)
|
||||||
|
print("Your ciphertext: ", ctext)
|
||||||
|
print("Your decrypted plaintext: ", aes_de(ctext, key))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
29
IS/Lab/Lab2/aes_192.py
Normal file
29
IS/Lab/Lab2/aes_192.py
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
from Crypto.Cipher import AES
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
|
||||||
|
def aes_cipher(key):
|
||||||
|
return AES.new(key.encode('utf-8'), AES.MODE_ECB)
|
||||||
|
|
||||||
|
def aes_en(ptext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
ptext = pad(ptext.encode('utf-8'), AES.block_size)
|
||||||
|
return cipher.encrypt(ptext)
|
||||||
|
|
||||||
|
def aes_de(ctext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
decrypted = cipher.decrypt(ctext)
|
||||||
|
return unpad(decrypted, AES.block_size).decode('utf-8')
|
||||||
|
|
||||||
|
def aespad_key(key):
|
||||||
|
return key.ljust(24)[:24]
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ptext = input("Enter plaintext: ")
|
||||||
|
key = input("Enter key: ")
|
||||||
|
key = aespad_key(key)
|
||||||
|
ctext = aes_en(ptext, key)
|
||||||
|
print("Ciphertext:", ctext.hex())
|
||||||
|
print("Decrypted:", aes_de(ctext, key))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
196
IS/Lab/Lab2/aes_des_bit.py
Normal file
196
IS/Lab/Lab2/aes_des_bit.py
Normal file
|
@ -0,0 +1,196 @@
|
||||||
|
from Crypto.Cipher import DES, DES3, AES
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
import time
|
||||||
|
from bokeh.plotting import figure, show, output_file
|
||||||
|
from bokeh.models import HoverTool, ColumnDataSource
|
||||||
|
from bokeh.layouts import column, row
|
||||||
|
import bokeh.palettes as bp
|
||||||
|
|
||||||
|
def pad_key(key, length):
|
||||||
|
return key.ljust(length)[:length].encode('utf-8')
|
||||||
|
|
||||||
|
def encrypt_with_timing(cipher_func, ptext, key, *args):
|
||||||
|
# Use more precise timing for microsecond measurements
|
||||||
|
start_time = time.perf_counter()
|
||||||
|
result = cipher_func(ptext, key, *args)
|
||||||
|
end_time = time.perf_counter()
|
||||||
|
return result, end_time - start_time
|
||||||
|
|
||||||
|
def des_encrypt(ptext, key, mode):
|
||||||
|
key = pad_key(key, 8)
|
||||||
|
cipher = DES.new(key, mode)
|
||||||
|
padded_text = pad(ptext.encode('utf-8'), DES.block_size)
|
||||||
|
return cipher.encrypt(padded_text)
|
||||||
|
|
||||||
|
def des3_encrypt(ptext, key, key_size, mode):
|
||||||
|
if key_size == 128:
|
||||||
|
key = pad_key(key, 16)
|
||||||
|
elif key_size == 192:
|
||||||
|
key = pad_key(key, 24)
|
||||||
|
else: # 256 bit uses 192 bit key (DES3 limitation)
|
||||||
|
key = pad_key(key, 24)
|
||||||
|
|
||||||
|
cipher = DES3.new(key, mode)
|
||||||
|
padded_text = pad(ptext.encode('utf-8'), DES3.block_size)
|
||||||
|
return cipher.encrypt(padded_text)
|
||||||
|
|
||||||
|
def aes_encrypt(ptext, key, key_size, mode):
|
||||||
|
if key_size == 128:
|
||||||
|
key = pad_key(key, 16)
|
||||||
|
elif key_size == 192:
|
||||||
|
key = pad_key(key, 24)
|
||||||
|
else: # 256
|
||||||
|
key = pad_key(key, 32)
|
||||||
|
|
||||||
|
cipher = AES.new(key, mode)
|
||||||
|
padded_text = pad(ptext.encode('utf-8'), AES.block_size)
|
||||||
|
return cipher.encrypt(padded_text)
|
||||||
|
|
||||||
|
def des_128(ptext, key, mode=DES.MODE_ECB):
|
||||||
|
return des_encrypt(ptext, key, mode)
|
||||||
|
|
||||||
|
def des_192(ptext, key, mode=DES3.MODE_ECB):
|
||||||
|
return des3_encrypt(ptext, key, 192, mode)
|
||||||
|
|
||||||
|
def des_256(ptext, key, mode=DES3.MODE_ECB):
|
||||||
|
return des3_encrypt(ptext, key, 256, mode)
|
||||||
|
|
||||||
|
def aes_128(ptext, key, mode=AES.MODE_ECB):
|
||||||
|
return aes_encrypt(ptext, key, 128, mode)
|
||||||
|
|
||||||
|
def aes_192(ptext, key, mode=AES.MODE_ECB):
|
||||||
|
return aes_encrypt(ptext, key, 192, mode)
|
||||||
|
|
||||||
|
def aes_256(ptext, key, mode=AES.MODE_ECB):
|
||||||
|
return aes_encrypt(ptext, key, 256, mode)
|
||||||
|
|
||||||
|
def bokeh_graph(timing_data):
|
||||||
|
output_file("encryption_performance.html")
|
||||||
|
|
||||||
|
from bokeh.models import LinearColorMapper, ColorBar, BasicTicker, PrintfTickFormatter
|
||||||
|
from bokeh.transform import transform
|
||||||
|
import math
|
||||||
|
|
||||||
|
algorithms = list(timing_data.keys())
|
||||||
|
messages = [f"Msg {i+1}" for i in range(len(next(iter(timing_data.values()))))]
|
||||||
|
|
||||||
|
# Convert all times to microseconds for better visibility
|
||||||
|
def to_microseconds(seconds):
|
||||||
|
return seconds * 1_000_000
|
||||||
|
|
||||||
|
# Chart 2: Performance variability - Box plot style using circles and lines
|
||||||
|
p2 = figure(x_range=algorithms, title="Performance Distribution Across Messages",
|
||||||
|
toolbar_location=None, tools="", width=800, height=400)
|
||||||
|
|
||||||
|
for i, algo_name in enumerate(algorithms):
|
||||||
|
times_us = [to_microseconds(t) for t in timing_data[algo_name]]
|
||||||
|
|
||||||
|
# Calculate statistics
|
||||||
|
mean_time = sum(times_us) / len(times_us)
|
||||||
|
min_time = min(times_us)
|
||||||
|
max_time = max(times_us)
|
||||||
|
|
||||||
|
# Plot range line
|
||||||
|
p2.line([i, i], [min_time, max_time], line_width=2, color=colors[i], alpha=0.6)
|
||||||
|
|
||||||
|
# Plot individual points
|
||||||
|
y_positions = times_us
|
||||||
|
x_positions = [i + (j - 2) * 0.1 for j in range(len(times_us))] # Spread points horizontally
|
||||||
|
p2.circle(x_positions, y_positions, size=8, color=colors[i], alpha=0.8)
|
||||||
|
|
||||||
|
# Plot mean as a diamond
|
||||||
|
p2.diamond([i], [mean_time], size=12, color=colors[i], line_color="black", line_width=1)
|
||||||
|
|
||||||
|
p2.xaxis.major_label_orientation = 45
|
||||||
|
p2.yaxis.axis_label = "Execution Time (microseconds)"
|
||||||
|
p2.xaxis.axis_label = "Encryption Algorithm"
|
||||||
|
p2.xaxis.ticker = BasicTicker()
|
||||||
|
p2.xaxis.formatter = PrintfTickFormatter(format="%s")
|
||||||
|
|
||||||
|
hover2 = HoverTool(tooltips=[("Time (μs)", "@y{0.00}")], mode='vline')
|
||||||
|
p2.add_tools(hover2)
|
||||||
|
|
||||||
|
# Chart 4: Relative performance comparison (normalized to fastest)
|
||||||
|
p4 = figure(x_range=algorithms, title="Relative Performance (Normalized to Fastest Algorithm)",
|
||||||
|
toolbar_location=None, tools="", width=800, height=400)
|
||||||
|
|
||||||
|
# Find the fastest average time
|
||||||
|
fastest_avg = min(avg_times)
|
||||||
|
relative_times = [avg / fastest_avg for avg in avg_times]
|
||||||
|
|
||||||
|
bars4 = p4.vbar(x=algorithms, top=relative_times, width=0.6, color=colors, alpha=0.8)
|
||||||
|
|
||||||
|
# Add reference line at 1.0
|
||||||
|
p4.line([-0.5, len(algorithms)-0.5], [1, 1], line_dash="dashed", line_width=2, color="red", alpha=0.7)
|
||||||
|
|
||||||
|
p4.xaxis.major_label_orientation = 45
|
||||||
|
p4.yaxis.axis_label = "Relative Performance (1.0 = fastest)"
|
||||||
|
p4.xaxis.axis_label = "Encryption Algorithm"
|
||||||
|
|
||||||
|
hover4 = HoverTool(tooltips=[("Algorithm", "@x"), ("Relative Speed", "@top{0.00}x")], renderers=[bars4])
|
||||||
|
p4.add_tools(hover4)
|
||||||
|
|
||||||
|
# Layout all charts
|
||||||
|
layout = column(
|
||||||
|
row(p2),
|
||||||
|
row(p4)
|
||||||
|
)
|
||||||
|
|
||||||
|
show(layout)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("The AES/DES Encryptor with Performance Analysis")
|
||||||
|
|
||||||
|
# Get exactly 5 messages from user
|
||||||
|
messages = []
|
||||||
|
print("\nEnter exactly 5 messages to encrypt:")
|
||||||
|
for i in range(5):
|
||||||
|
while True:
|
||||||
|
message = input(f"Message {i+1}: ")
|
||||||
|
if message.strip(): # Only accept non-empty messages
|
||||||
|
messages.append(message)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
print("Please enter a non-empty message.")
|
||||||
|
|
||||||
|
key = input("\nEnter key: ")
|
||||||
|
|
||||||
|
# Define algorithms to test (using ECB mode only)
|
||||||
|
algorithms = [
|
||||||
|
('DES', des_128, DES.MODE_ECB),
|
||||||
|
('DES3-192', des_192, DES3.MODE_ECB),
|
||||||
|
('AES-128', aes_128, AES.MODE_ECB),
|
||||||
|
('AES-192', aes_192, AES.MODE_ECB),
|
||||||
|
('AES-256', aes_256, AES.MODE_ECB)
|
||||||
|
]
|
||||||
|
|
||||||
|
timing_data = {}
|
||||||
|
|
||||||
|
print("\nEncrypting messages and measuring performance...\n")
|
||||||
|
|
||||||
|
# Run each message through each algorithm multiple times for better precision
|
||||||
|
for algo_name, algo_func, mode in algorithms:
|
||||||
|
timing_data[algo_name] = []
|
||||||
|
print(f"=== {algo_name} ===")
|
||||||
|
|
||||||
|
for i, message in enumerate(messages):
|
||||||
|
print(f"Message {i+1}: {message[:30]}...")
|
||||||
|
|
||||||
|
# Run multiple times and take the best time to reduce noise
|
||||||
|
best_time = float('inf')
|
||||||
|
for _ in range(10): # 10 runs for better precision
|
||||||
|
ctext, exec_time = encrypt_with_timing(algo_func, message, key, mode)
|
||||||
|
best_time = min(best_time, exec_time)
|
||||||
|
|
||||||
|
print(f"{algo_name}: {best_time:.8f}s ({best_time*1000000:.2f}μs)")
|
||||||
|
timing_data[algo_name].append(best_time)
|
||||||
|
|
||||||
|
print()
|
||||||
|
|
||||||
|
# Generate performance graphs
|
||||||
|
print("Generating performance visualization...")
|
||||||
|
bokeh_graph(timing_data)
|
||||||
|
print("Performance graphs saved to 'encryption_performance.html'")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
30
IS/Lab/Lab2/des.py
Normal file
30
IS/Lab/Lab2/des.py
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
from Crypto.Cipher import DES
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
|
||||||
|
def des_cipher(key):
|
||||||
|
return DES.new(key.encode('utf-8'), DES.MODE_ECB)
|
||||||
|
|
||||||
|
def des_en(ptext, key):
|
||||||
|
cipher = des_cipher(key)
|
||||||
|
padded_text = pad(ptext.encode('utf-8'), DES.block_size)
|
||||||
|
return cipher.encrypt(padded_text)
|
||||||
|
|
||||||
|
def des_de(ctext, key):
|
||||||
|
cipher = des_cipher(key)
|
||||||
|
decrypted = unpad(cipher.decrypt(ctext), DES.block_size)
|
||||||
|
return decrypted.decode('utf-8')
|
||||||
|
|
||||||
|
def despad_key(key):
|
||||||
|
return key.ljust(8)[:8]
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Welcome to DES (Original)")
|
||||||
|
ptext = input("Enter plaintext: ")
|
||||||
|
key = input("Enter key: ")
|
||||||
|
key = despad_key(key)
|
||||||
|
ctext = des_en(ptext, key)
|
||||||
|
print("Your ciphertext: ", ctext)
|
||||||
|
print("Your decrypted plaintext: ", des_de(ctext, key))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
61
IS/Lab/Lab2/des_vs_aes256.html
Normal file
61
IS/Lab/Lab2/des_vs_aes256.html
Normal file
File diff suppressed because one or more lines are too long
176
IS/Lab/Lab2/des_vs_aes256.py
Normal file
176
IS/Lab/Lab2/des_vs_aes256.py
Normal file
|
@ -0,0 +1,176 @@
|
||||||
|
import time
|
||||||
|
import numpy as np
|
||||||
|
from Crypto.Cipher import AES, DES
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
from bokeh.plotting import figure, show
|
||||||
|
from bokeh.models import HoverTool
|
||||||
|
from bokeh.layouts import column
|
||||||
|
from bokeh.palettes import Category10
|
||||||
|
|
||||||
|
def aes_cipher(key):
|
||||||
|
return AES.new(key.encode('utf-8'), AES.MODE_ECB)
|
||||||
|
|
||||||
|
def aes_en(ptext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
ptext = pad(ptext.encode('utf-8'), AES.block_size)
|
||||||
|
return cipher.encrypt(ptext)
|
||||||
|
|
||||||
|
def aes_de(ctext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
decrypted = cipher.decrypt(ctext)
|
||||||
|
return unpad(decrypted, AES.block_size).decode('utf-8')
|
||||||
|
|
||||||
|
def aes256_pad_key(key):
|
||||||
|
return key.ljust(32)[:32]
|
||||||
|
|
||||||
|
def des_cipher(key):
|
||||||
|
return DES.new(key.encode('utf-8'), DES.MODE_ECB)
|
||||||
|
|
||||||
|
def des_en(ptext, key):
|
||||||
|
cipher = des_cipher(key)
|
||||||
|
ptext = pad(ptext.encode('utf-8'), DES.block_size)
|
||||||
|
return cipher.encrypt(ptext)
|
||||||
|
|
||||||
|
def des_de(ctext, key):
|
||||||
|
cipher = des_cipher(key)
|
||||||
|
decrypted = cipher.decrypt(ctext)
|
||||||
|
return unpad(decrypted, DES.block_size).decode('utf-8')
|
||||||
|
|
||||||
|
def des_pad_key(key):
|
||||||
|
return key.ljust(8)[:8]
|
||||||
|
|
||||||
|
def time_encryption_progressive(encrypt_func, plaintext, key, max_iterations=1000):
|
||||||
|
"""Time encryption across different iteration counts"""
|
||||||
|
iteration_counts = np.logspace(1, np.log10(max_iterations), 10, dtype=int)
|
||||||
|
times_per_iteration = []
|
||||||
|
|
||||||
|
for iterations in iteration_counts:
|
||||||
|
start_time = time.time()
|
||||||
|
for _ in range(iterations):
|
||||||
|
encrypt_func(plaintext, key)
|
||||||
|
end_time = time.time()
|
||||||
|
total_time = end_time - start_time
|
||||||
|
times_per_iteration.append(total_time / iterations)
|
||||||
|
|
||||||
|
return iteration_counts, times_per_iteration
|
||||||
|
|
||||||
|
def time_decryption_progressive(decrypt_func, ciphertext, key, max_iterations=1000):
|
||||||
|
"""Time decryption across different iteration counts"""
|
||||||
|
iteration_counts = np.logspace(1, np.log10(max_iterations), 10, dtype=int)
|
||||||
|
times_per_iteration = []
|
||||||
|
|
||||||
|
for iterations in iteration_counts:
|
||||||
|
start_time = time.time()
|
||||||
|
for _ in range(iterations):
|
||||||
|
decrypt_func(ciphertext, key)
|
||||||
|
end_time = time.time()
|
||||||
|
total_time = end_time - start_time
|
||||||
|
times_per_iteration.append(total_time / iterations)
|
||||||
|
|
||||||
|
return iteration_counts, times_per_iteration
|
||||||
|
|
||||||
|
def benchmark_ciphers(plaintext, raw_key, max_iterations=1000):
|
||||||
|
# Prepare keys
|
||||||
|
aes_key = aes256_pad_key(raw_key)
|
||||||
|
des_key = des_pad_key(raw_key)
|
||||||
|
|
||||||
|
# Get ciphertexts for decryption timing
|
||||||
|
aes_ciphertext = aes_en(plaintext, aes_key)
|
||||||
|
des_ciphertext = des_en(plaintext, des_key)
|
||||||
|
|
||||||
|
# Time encryption progressively
|
||||||
|
aes_enc_iterations, aes_enc_times = time_encryption_progressive(aes_en, plaintext, aes_key, max_iterations)
|
||||||
|
des_enc_iterations, des_enc_times = time_encryption_progressive(des_en, plaintext, des_key, max_iterations)
|
||||||
|
|
||||||
|
# Time decryption progressively
|
||||||
|
aes_dec_iterations, aes_dec_times = time_decryption_progressive(aes_de, aes_ciphertext, aes_key, max_iterations)
|
||||||
|
des_dec_iterations, des_dec_times = time_decryption_progressive(des_de, des_ciphertext, des_key, max_iterations)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'aes_enc_iterations': aes_enc_iterations,
|
||||||
|
'aes_enc_times': aes_enc_times,
|
||||||
|
'des_enc_iterations': des_enc_iterations,
|
||||||
|
'des_enc_times': des_enc_times,
|
||||||
|
'aes_dec_iterations': aes_dec_iterations,
|
||||||
|
'aes_dec_times': aes_dec_times,
|
||||||
|
'des_dec_iterations': des_dec_iterations,
|
||||||
|
'des_dec_times': des_dec_times
|
||||||
|
}
|
||||||
|
|
||||||
|
def create_plot(title, plaintext_length):
|
||||||
|
return figure(
|
||||||
|
title=f"{title}\nPlaintext length: {plaintext_length} chars",
|
||||||
|
x_axis_label="Number of Iterations",
|
||||||
|
y_axis_label="Time per Operation (seconds)",
|
||||||
|
x_axis_type="log",
|
||||||
|
y_axis_type="log",
|
||||||
|
width=800,
|
||||||
|
height=400,
|
||||||
|
background_fill_color="#fafafa",
|
||||||
|
border_fill_color="whitesmoke"
|
||||||
|
)
|
||||||
|
|
||||||
|
def add_line_and_markers(plot, x_data, y_data, color, label):
|
||||||
|
plot.line(x_data, y_data, line_width=3, color=color, alpha=0.8, legend_label=label)
|
||||||
|
plot.scatter(x_data, y_data, size=8, color=color, alpha=0.8)
|
||||||
|
|
||||||
|
def plot_results(results, plaintext_length):
|
||||||
|
colors = Category10[4]
|
||||||
|
|
||||||
|
# Create plots
|
||||||
|
p1 = create_plot("Encryption Performance: Time per Operation", plaintext_length)
|
||||||
|
p2 = create_plot("Decryption Performance: Time per Operation", plaintext_length)
|
||||||
|
|
||||||
|
# Add data to plots
|
||||||
|
add_line_and_markers(p1, results['aes_enc_iterations'], results['aes_enc_times'], colors[0], "AES-256 Encryption")
|
||||||
|
add_line_and_markers(p1, results['des_enc_iterations'], results['des_enc_times'], colors[1], "DES Encryption")
|
||||||
|
add_line_and_markers(p2, results['aes_dec_iterations'], results['aes_dec_times'], colors[2], "AES-256 Decryption")
|
||||||
|
add_line_and_markers(p2, results['des_dec_iterations'], results['des_dec_times'], colors[3], "DES Decryption")
|
||||||
|
|
||||||
|
# Add hover tools and styling
|
||||||
|
hover = HoverTool(tooltips=[("Algorithm", "@legend_label"), ("Iterations", "@x"), ("Time per Op", "@y{0.0000000} sec")])
|
||||||
|
|
||||||
|
for p in [p1, p2]:
|
||||||
|
p.add_tools(hover)
|
||||||
|
p.legend.location = "top_right"
|
||||||
|
p.legend.click_policy = "hide"
|
||||||
|
p.legend.background_fill_alpha = 0.8
|
||||||
|
p.grid.grid_line_alpha = 0.3
|
||||||
|
|
||||||
|
show(column(p1, p2))
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("AES-256 vs DES Performance Comparison")
|
||||||
|
print("=====================================")
|
||||||
|
|
||||||
|
plaintext = input("Enter plaintext: ")
|
||||||
|
key = input("Enter key: ")
|
||||||
|
max_iterations = int(input("Enter maximum number of iterations (default 1000): ") or "1000")
|
||||||
|
|
||||||
|
print(f"\nBenchmarking across iteration ranges up to {max_iterations}...")
|
||||||
|
results = benchmark_ciphers(plaintext, key, max_iterations)
|
||||||
|
|
||||||
|
# Calculate average times for comparison
|
||||||
|
avg_aes_enc = np.mean(results['aes_enc_times'])
|
||||||
|
avg_des_enc = np.mean(results['des_enc_times'])
|
||||||
|
avg_aes_dec = np.mean(results['aes_dec_times'])
|
||||||
|
avg_des_dec = np.mean(results['des_dec_times'])
|
||||||
|
|
||||||
|
print("\nAverage Results (time per operation):")
|
||||||
|
print(f"AES-256 Encryption: {avg_aes_enc:.8f} seconds")
|
||||||
|
print(f"DES Encryption: {avg_des_enc:.8f} seconds")
|
||||||
|
print(f"AES-256 Decryption: {avg_aes_dec:.8f} seconds")
|
||||||
|
print(f"DES Decryption: {avg_des_dec:.8f} seconds")
|
||||||
|
|
||||||
|
print("\nSpeed comparison:")
|
||||||
|
if avg_aes_enc < avg_des_enc:
|
||||||
|
ratio = avg_des_enc / avg_aes_enc
|
||||||
|
print(f"AES-256 encryption is {ratio:.2f}x faster than DES")
|
||||||
|
else:
|
||||||
|
ratio = avg_aes_enc / avg_des_enc
|
||||||
|
print(f"DES encryption is {ratio:.2f}x faster than AES-256")
|
||||||
|
|
||||||
|
plot_results(results, len(plaintext))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
61
IS/Lab/Lab2/encryption_performance.html
Normal file
61
IS/Lab/Lab2/encryption_performance.html
Normal file
File diff suppressed because one or more lines are too long
61
IS/Lab/Lab2/multiround_aes_192
Normal file
61
IS/Lab/Lab2/multiround_aes_192
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
from Crypto.Cipher import AES
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
|
||||||
|
def aes_cipher(key):
|
||||||
|
return AES.new(key.encode('utf-8'), AES.MODE_ECB)
|
||||||
|
|
||||||
|
def aes_en(ptext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
ptext = pad(ptext.encode('utf-8'), AES.block_size)
|
||||||
|
return cipher.encrypt(ptext)
|
||||||
|
|
||||||
|
def aes_de(ctext, key):
|
||||||
|
cipher = aes_cipher(key)
|
||||||
|
decrypted = cipher.decrypt(ctext)
|
||||||
|
return unpad(decrypted, AES.block_size).decode('utf-8')
|
||||||
|
|
||||||
|
def aespad_key(key):
|
||||||
|
return key.ljust(24)[:24]
|
||||||
|
|
||||||
|
def aes_en_trace(ptext, key):
|
||||||
|
key = aespad_key(key)
|
||||||
|
key_bytes = key.encode('utf-8')
|
||||||
|
cipher = AES.new(key_bytes, AES.MODE_ECB)
|
||||||
|
blocks = pad(ptext.encode('utf-8'), AES.block_size)
|
||||||
|
|
||||||
|
print("AES-192 (ECB) concise steps:")
|
||||||
|
print(" • Key expansion: Nk=6, Nb=4, Nr=12 → 13 round keys")
|
||||||
|
print(" • Initial round: AddRoundKey")
|
||||||
|
print(" • Main rounds (1..11): SubBytes → ShiftRows → MixColumns → AddRoundKey")
|
||||||
|
print(" • Final round (12): SubBytes → ShiftRows → AddRoundKey\n")
|
||||||
|
|
||||||
|
out = bytearray()
|
||||||
|
for i in range(0, len(blocks), 16):
|
||||||
|
block = blocks[i:i+16]
|
||||||
|
print(f"Block {i//16} plaintext: {block.hex()}")
|
||||||
|
print(" Round 0: AddRoundKey")
|
||||||
|
for r in range(1, 12):
|
||||||
|
print(f" Round {r}: SubBytes → ShiftRows → MixColumns → AddRoundKey")
|
||||||
|
print(" Round 12: SubBytes → ShiftRows → AddRoundKey")
|
||||||
|
cblock = cipher.encrypt(block)
|
||||||
|
print(f" Ciphertext block: {cblock.hex()}\n")
|
||||||
|
out.extend(cblock)
|
||||||
|
return bytes(out)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
default_pt = "MIT AES DEMO"
|
||||||
|
default_key = "MIT-AES-192-DEMO-KEY-24!"
|
||||||
|
|
||||||
|
ptext = input(f"Enter plaintext (blank={default_pt}): ").strip()
|
||||||
|
key = input(f"Enter key (blank={default_key}): ").strip()
|
||||||
|
if not ptext:
|
||||||
|
ptext = default_pt
|
||||||
|
if not key:
|
||||||
|
key = default_key
|
||||||
|
|
||||||
|
ctext = aes_en_trace(ptext, key)
|
||||||
|
print("Ciphertext:", ctext.hex())
|
||||||
|
print("Decrypted:", aes_de(ctext, aespad_key(key)))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
109
IS/Lab/Lab3/DiffieHellman.py
Normal file
109
IS/Lab/Lab3/DiffieHellman.py
Normal file
|
@ -0,0 +1,109 @@
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from Crypto.Hash import SHA256
|
||||||
|
from Crypto.Protocol.KDF import HKDF
|
||||||
|
from Crypto.Util import number
|
||||||
|
|
||||||
|
|
||||||
|
def rfc3526_group14() -> tuple[int, int]:
|
||||||
|
"""
|
||||||
|
Return the 2048-bit MODP Group (Group 14) parameters from RFC 3526.
|
||||||
|
|
||||||
|
g = 2
|
||||||
|
p is the safe prime specified in RFC 3526, section 3.
|
||||||
|
"""
|
||||||
|
# RFC 3526 Group 14 (2048-bit MODP) prime (hex, concatenated)
|
||||||
|
p_hex = (
|
||||||
|
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
|
||||||
|
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
|
||||||
|
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
|
||||||
|
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
|
||||||
|
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
|
||||||
|
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
|
||||||
|
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
|
||||||
|
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
|
||||||
|
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
|
||||||
|
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
|
||||||
|
"15728E5A8AACAA68FFFFFFFFFFFFFFFF"
|
||||||
|
)
|
||||||
|
p = int(p_hex, 16)
|
||||||
|
g = 2
|
||||||
|
return p, g
|
||||||
|
|
||||||
|
|
||||||
|
def int_to_fixed_length_bytes(value: int, length_bits: int) -> bytes:
|
||||||
|
length_bytes = (length_bits + 7) // 8
|
||||||
|
return value.to_bytes(length_bytes, byteorder="big")
|
||||||
|
|
||||||
|
|
||||||
|
def generate_keypair(p: int, g: int, private_bits: int = 256) -> tuple[int, int]:
|
||||||
|
a = 0
|
||||||
|
while a < 2:
|
||||||
|
a = number.getRandomNBitInteger(private_bits)
|
||||||
|
A = pow(g, a, p)
|
||||||
|
return a, A
|
||||||
|
|
||||||
|
|
||||||
|
def derive_shared_key(peer_public: int, private: int, p: int, key_len: int = 32) -> bytes:
|
||||||
|
shared_secret = pow(peer_public, private, p)
|
||||||
|
# Use fixed-length big-endian encoding of the shared secret for KDF input
|
||||||
|
shared_bytes = int_to_fixed_length_bytes(shared_secret, p.bit_length())
|
||||||
|
key = HKDF(shared_bytes, key_len, salt=None, hashmod=SHA256, context=b"DH key")
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
class TimingResult:
|
||||||
|
alice_keygen_s: float
|
||||||
|
bob_keygen_s: float
|
||||||
|
alice_exchange_s: float
|
||||||
|
bob_exchange_s: float
|
||||||
|
|
||||||
|
|
||||||
|
def measure_timings(p: int, g: int, private_bits: int = 256) -> TimingResult:
|
||||||
|
start = time.perf_counter()
|
||||||
|
a_priv, a_pub = generate_keypair(p, g, private_bits)
|
||||||
|
alice_keygen_s = time.perf_counter() - start
|
||||||
|
|
||||||
|
start = time.perf_counter()
|
||||||
|
b_priv, b_pub = generate_keypair(p, g, private_bits)
|
||||||
|
bob_keygen_s = time.perf_counter() - start
|
||||||
|
|
||||||
|
# Exchange
|
||||||
|
start = time.perf_counter()
|
||||||
|
a_key = derive_shared_key(b_pub, a_priv, p)
|
||||||
|
alice_exchange_s = time.perf_counter() - start
|
||||||
|
|
||||||
|
start = time.perf_counter()
|
||||||
|
b_key = derive_shared_key(a_pub, b_priv, p)
|
||||||
|
bob_exchange_s = time.perf_counter() - start
|
||||||
|
|
||||||
|
# Sanity check
|
||||||
|
if a_key != b_key:
|
||||||
|
raise RuntimeError("Derived keys do not match. Check parameters.")
|
||||||
|
|
||||||
|
return TimingResult(
|
||||||
|
alice_keygen_s=alice_keygen_s,
|
||||||
|
bob_keygen_s=bob_keygen_s,
|
||||||
|
alice_exchange_s=alice_exchange_s,
|
||||||
|
bob_exchange_s=bob_exchange_s,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
p, g = rfc3526_group14()
|
||||||
|
|
||||||
|
timings = measure_timings(p, g, private_bits=256)
|
||||||
|
|
||||||
|
print("Diffie-Hellman (RFC3526 Group 14, g=2)")
|
||||||
|
print(f"Prime bits: {p.bit_length()}\n")
|
||||||
|
|
||||||
|
print("Timings (seconds):")
|
||||||
|
print(f"- Alice key generation: {timings.alice_keygen_s:.6f}")
|
||||||
|
print(f"- Bob key generation: {timings.bob_keygen_s:.6f}")
|
||||||
|
print(f"- Alice key exchange: {timings.alice_exchange_s:.6f}")
|
||||||
|
print(f"- Bob key exchange: {timings.bob_exchange_s:.6f}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
58
IS/Lab/Lab3/ECC.py
Normal file
58
IS/Lab/Lab3/ECC.py
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
from Crypto.PublicKey import ECC
|
||||||
|
from Crypto.Cipher import AES
|
||||||
|
from Crypto.Hash import SHA256
|
||||||
|
import binascii
|
||||||
|
|
||||||
|
|
||||||
|
def ecc_keygen(curve: str = 'P-256') -> ECC.EccKey:
|
||||||
|
return ECC.generate(curve=curve)
|
||||||
|
|
||||||
|
|
||||||
|
def ecc_encrypt(plaintext: str, recipient_public_key: ECC.EccKey):
|
||||||
|
eph_private = ECC.generate(curve=recipient_public_key.curve)
|
||||||
|
shared_point = recipient_public_key.pointQ * eph_private.d
|
||||||
|
shared_x = int(shared_point.x)
|
||||||
|
aes_key = SHA256.new(shared_x.to_bytes(32, 'big')).digest()
|
||||||
|
|
||||||
|
cipher = AES.new(aes_key, AES.MODE_GCM)
|
||||||
|
ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode('utf-8'))
|
||||||
|
|
||||||
|
return {
|
||||||
|
'ephemeral_pub_der': eph_private.public_key().export_key(format='DER'),
|
||||||
|
'nonce': cipher.nonce,
|
||||||
|
'tag': tag,
|
||||||
|
'ciphertext': ciphertext,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def ecc_decrypt(enc: dict, recipient_private_key: ECC.EccKey) -> str:
|
||||||
|
eph_public = ECC.import_key(enc['ephemeral_pub_der'])
|
||||||
|
shared_point = eph_public.pointQ * recipient_private_key.d
|
||||||
|
shared_x = int(shared_point.x)
|
||||||
|
aes_key = SHA256.new(shared_x.to_bytes(32, 'big')).digest()
|
||||||
|
|
||||||
|
cipher = AES.new(aes_key, AES.MODE_GCM, nonce=enc['nonce'])
|
||||||
|
plaintext = cipher.decrypt_and_verify(enc['ciphertext'], enc['tag'])
|
||||||
|
return plaintext.decode('utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print('Welcome to ECC (ECIES-style)')
|
||||||
|
ptext = input('Enter plaintext: ')
|
||||||
|
|
||||||
|
priv_key = ecc_keygen()
|
||||||
|
pub_key = priv_key.public_key()
|
||||||
|
|
||||||
|
print('\nPublic Key (Qx, Qy):')
|
||||||
|
print('Qx =', hex(int(pub_key.pointQ.x)))
|
||||||
|
print('Qy =', hex(int(pub_key.pointQ.y)))
|
||||||
|
|
||||||
|
enc = ecc_encrypt(ptext, pub_key)
|
||||||
|
print("\nYour ciphertext (hex):", binascii.hexlify(enc['ciphertext']).decode())
|
||||||
|
|
||||||
|
decrypted = ecc_decrypt(enc, priv_key)
|
||||||
|
print('Your decrypted plaintext:', decrypted)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
57
IS/Lab/Lab3/ElGamal.py
Normal file
57
IS/Lab/Lab3/ElGamal.py
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
import random
|
||||||
|
from Crypto.Util.number import getPrime
|
||||||
|
|
||||||
|
def elgamal_keygen(bits=512):
|
||||||
|
p = getPrime(bits)
|
||||||
|
g = random.randint(2, p-1)
|
||||||
|
x = random.randint(1, p-2) # private key
|
||||||
|
h = pow(g, x, p) # public key component
|
||||||
|
return (p, g, h), x
|
||||||
|
|
||||||
|
def elgamal_encrypt(message, pub_key):
|
||||||
|
p, g, h = pub_key
|
||||||
|
m = int.from_bytes(message.encode('utf-8'), 'big')
|
||||||
|
if m >= p:
|
||||||
|
raise ValueError("Message too large for key size")
|
||||||
|
|
||||||
|
k = random.randint(1, p-2)
|
||||||
|
c1 = pow(g, k, p)
|
||||||
|
c2 = (m * pow(h, k, p)) % p
|
||||||
|
return (c1, c2)
|
||||||
|
|
||||||
|
def elgamal_decrypt(ciphertext, priv_key, pub_key):
|
||||||
|
c1, c2 = ciphertext
|
||||||
|
p, g, h = pub_key
|
||||||
|
x = priv_key
|
||||||
|
|
||||||
|
s = pow(c1, x, p)
|
||||||
|
s_inv = pow(s, p-2, p) # modular inverse
|
||||||
|
m = (c2 * s_inv) % p
|
||||||
|
|
||||||
|
return m.to_bytes((m.bit_length() + 7) // 8, 'big').decode('utf-8')
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Welcome to ElGamal")
|
||||||
|
ptext = input("Enter plaintext: ")
|
||||||
|
|
||||||
|
# Generate keys
|
||||||
|
pub_key, priv_key = elgamal_keygen()
|
||||||
|
p, g, h = pub_key
|
||||||
|
|
||||||
|
print(f"\nPublic Key (p, g, h):")
|
||||||
|
print(f"p = {hex(p)}")
|
||||||
|
print(f"g = {g}")
|
||||||
|
print(f"h = {hex(h)}")
|
||||||
|
|
||||||
|
# Encrypt
|
||||||
|
ctext = elgamal_encrypt(ptext, pub_key)
|
||||||
|
print(f"\nCiphertext (c1, c2):")
|
||||||
|
print(f"c1 = {hex(ctext[0])}")
|
||||||
|
print(f"c2 = {hex(ctext[1])}")
|
||||||
|
|
||||||
|
# Decrypt
|
||||||
|
decrypted = elgamal_decrypt(ctext, priv_key, pub_key)
|
||||||
|
print(f"Decrypted: {decrypted}")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
299
IS/Lab/Lab3/FileTransfer.py
Normal file
299
IS/Lab/Lab3/FileTransfer.py
Normal file
|
@ -0,0 +1,299 @@
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import binascii
|
||||||
|
from Crypto.PublicKey import RSA, ECC
|
||||||
|
from Crypto.Cipher import PKCS1_OAEP, AES
|
||||||
|
from Crypto.Hash import SHA256
|
||||||
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
from Crypto.Random import get_random_bytes
|
||||||
|
from bokeh.plotting import figure, show, output_file
|
||||||
|
from bokeh.layouts import gridplot
|
||||||
|
from bokeh.models import HoverTool
|
||||||
|
|
||||||
|
|
||||||
|
def generate_test_file(size_mb):
|
||||||
|
"""Generate test file of specified size in MB"""
|
||||||
|
filename = f"test_file_{size_mb}MB.txt"
|
||||||
|
with open(filename, 'wb') as f:
|
||||||
|
# Write random data
|
||||||
|
for _ in range(size_mb * 1024): # 1MB = 1024KB
|
||||||
|
f.write(get_random_bytes(1024))
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
|
def rsa_keygen_timed():
|
||||||
|
"""Generate RSA key pair and measure time"""
|
||||||
|
start = time.time()
|
||||||
|
key = RSA.generate(2048)
|
||||||
|
gen_time = time.time() - start
|
||||||
|
return key, gen_time
|
||||||
|
|
||||||
|
|
||||||
|
def ecc_keygen_timed():
|
||||||
|
"""Generate ECC key pair and measure time"""
|
||||||
|
start = time.time()
|
||||||
|
key = ECC.generate(curve='secp256r1')
|
||||||
|
gen_time = time.time() - start
|
||||||
|
return key, gen_time
|
||||||
|
|
||||||
|
|
||||||
|
def rsa_encrypt_file(filename, pub_key):
|
||||||
|
"""Encrypt file using RSA with AES hybrid encryption"""
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
# Generate AES key
|
||||||
|
aes_key = get_random_bytes(32) # 256-bit AES key
|
||||||
|
|
||||||
|
# Encrypt AES key with RSA
|
||||||
|
rsa_cipher = PKCS1_OAEP.new(pub_key)
|
||||||
|
encrypted_aes_key = rsa_cipher.encrypt(aes_key)
|
||||||
|
|
||||||
|
# Encrypt file with AES
|
||||||
|
aes_cipher = AES.new(aes_key, AES.MODE_CBC)
|
||||||
|
iv = aes_cipher.iv
|
||||||
|
|
||||||
|
with open(filename, 'rb') as f:
|
||||||
|
plaintext = f.read()
|
||||||
|
|
||||||
|
padded_plaintext = pad(plaintext, AES.block_size)
|
||||||
|
ciphertext = aes_cipher.encrypt(padded_plaintext)
|
||||||
|
|
||||||
|
enc_time = time.time() - start
|
||||||
|
|
||||||
|
encrypted_data = {
|
||||||
|
'encrypted_aes_key': encrypted_aes_key,
|
||||||
|
'iv': iv,
|
||||||
|
'ciphertext': ciphertext
|
||||||
|
}
|
||||||
|
|
||||||
|
return encrypted_data, enc_time
|
||||||
|
|
||||||
|
|
||||||
|
def rsa_decrypt_file(encrypted_data, priv_key):
|
||||||
|
"""Decrypt file using RSA with AES hybrid decryption"""
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
# Decrypt AES key with RSA
|
||||||
|
rsa_cipher = PKCS1_OAEP.new(priv_key)
|
||||||
|
aes_key = rsa_cipher.decrypt(encrypted_data['encrypted_aes_key'])
|
||||||
|
|
||||||
|
# Decrypt file with AES
|
||||||
|
aes_cipher = AES.new(aes_key, AES.MODE_CBC, encrypted_data['iv'])
|
||||||
|
padded_plaintext = aes_cipher.decrypt(encrypted_data['ciphertext'])
|
||||||
|
plaintext = unpad(padded_plaintext, AES.block_size)
|
||||||
|
|
||||||
|
dec_time = time.time() - start
|
||||||
|
return plaintext, dec_time
|
||||||
|
|
||||||
|
|
||||||
|
def ecc_encrypt_file(filename, pub_key):
|
||||||
|
"""Encrypt file using ECC with AES hybrid encryption"""
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
# Generate ephemeral key pair
|
||||||
|
eph_private = ECC.generate(curve='secp256r1')
|
||||||
|
|
||||||
|
# Compute shared secret
|
||||||
|
shared_point = pub_key.pointQ * eph_private.d
|
||||||
|
shared_x = int(shared_point.x)
|
||||||
|
aes_key = SHA256.new(shared_x.to_bytes(32, 'big')).digest()
|
||||||
|
|
||||||
|
# Encrypt file with AES
|
||||||
|
aes_cipher = AES.new(aes_key, AES.MODE_GCM)
|
||||||
|
|
||||||
|
with open(filename, 'rb') as f:
|
||||||
|
plaintext = f.read()
|
||||||
|
|
||||||
|
ciphertext, tag = aes_cipher.encrypt_and_digest(plaintext)
|
||||||
|
|
||||||
|
enc_time = time.time() - start
|
||||||
|
|
||||||
|
encrypted_data = {
|
||||||
|
'ephemeral_pub_der': eph_private.public_key().export_key(format='DER'),
|
||||||
|
'nonce': aes_cipher.nonce,
|
||||||
|
'tag': tag,
|
||||||
|
'ciphertext': ciphertext
|
||||||
|
}
|
||||||
|
|
||||||
|
return encrypted_data, enc_time
|
||||||
|
|
||||||
|
|
||||||
|
def ecc_decrypt_file(encrypted_data, priv_key):
|
||||||
|
"""Decrypt file using ECC with AES hybrid decryption"""
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
# Import ephemeral public key
|
||||||
|
eph_public = ECC.import_key(encrypted_data['ephemeral_pub_der'])
|
||||||
|
|
||||||
|
# Compute shared secret
|
||||||
|
shared_point = eph_public.pointQ * priv_key.d
|
||||||
|
shared_x = int(shared_point.x)
|
||||||
|
aes_key = SHA256.new(shared_x.to_bytes(32, 'big')).digest()
|
||||||
|
|
||||||
|
# Decrypt file with AES
|
||||||
|
aes_cipher = AES.new(aes_key, AES.MODE_GCM, nonce=encrypted_data['nonce'])
|
||||||
|
plaintext = aes_cipher.decrypt_and_verify(encrypted_data['ciphertext'], encrypted_data['tag'])
|
||||||
|
|
||||||
|
dec_time = time.time() - start
|
||||||
|
return plaintext, dec_time
|
||||||
|
|
||||||
|
|
||||||
|
def measure_performance(file_sizes):
|
||||||
|
"""Measure performance for both RSA and ECC"""
|
||||||
|
results = {
|
||||||
|
'file_sizes': file_sizes,
|
||||||
|
'rsa_keygen': [],
|
||||||
|
'ecc_keygen': [],
|
||||||
|
'rsa_encrypt': [],
|
||||||
|
'rsa_decrypt': [],
|
||||||
|
'ecc_encrypt': [],
|
||||||
|
'ecc_decrypt': [],
|
||||||
|
'rsa_key_size': 0,
|
||||||
|
'ecc_key_size': 0
|
||||||
|
}
|
||||||
|
|
||||||
|
print("Performance Testing - RSA vs ECC File Transfer")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
# Generate keys once
|
||||||
|
rsa_key, rsa_keygen_time = rsa_keygen_timed()
|
||||||
|
ecc_key, ecc_keygen_time = ecc_keygen_timed()
|
||||||
|
|
||||||
|
# Calculate key sizes
|
||||||
|
results['rsa_key_size'] = len(rsa_key.export_key('DER'))
|
||||||
|
results['ecc_key_size'] = len(ecc_key.export_key(format='DER'))
|
||||||
|
|
||||||
|
print(f"RSA Key Generation Time: {rsa_keygen_time:.4f} seconds")
|
||||||
|
print(f"ECC Key Generation Time: {ecc_keygen_time:.4f} seconds")
|
||||||
|
print(f"RSA Key Size: {results['rsa_key_size']} bytes")
|
||||||
|
print(f"ECC Key Size: {results['ecc_key_size']} bytes")
|
||||||
|
print()
|
||||||
|
|
||||||
|
for size in file_sizes:
|
||||||
|
print(f"Testing {size}MB file...")
|
||||||
|
|
||||||
|
# Generate test file
|
||||||
|
filename = generate_test_file(size)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# RSA performance
|
||||||
|
rsa_pub = rsa_key.publickey()
|
||||||
|
encrypted_rsa, rsa_enc_time = rsa_encrypt_file(filename, rsa_pub)
|
||||||
|
decrypted_rsa, rsa_dec_time = rsa_decrypt_file(encrypted_rsa, rsa_key)
|
||||||
|
|
||||||
|
# ECC performance
|
||||||
|
ecc_pub = ecc_key.public_key()
|
||||||
|
encrypted_ecc, ecc_enc_time = ecc_encrypt_file(filename, ecc_pub)
|
||||||
|
decrypted_ecc, ecc_dec_time = ecc_decrypt_file(encrypted_ecc, ecc_key)
|
||||||
|
|
||||||
|
# Store results
|
||||||
|
results['rsa_keygen'].append(rsa_keygen_time)
|
||||||
|
results['ecc_keygen'].append(ecc_keygen_time)
|
||||||
|
results['rsa_encrypt'].append(rsa_enc_time)
|
||||||
|
results['rsa_decrypt'].append(rsa_dec_time)
|
||||||
|
results['ecc_encrypt'].append(ecc_enc_time)
|
||||||
|
results['ecc_decrypt'].append(ecc_dec_time)
|
||||||
|
|
||||||
|
print(f" RSA - Encrypt: {rsa_enc_time:.4f}s, Decrypt: {rsa_dec_time:.4f}s")
|
||||||
|
print(f" ECC - Encrypt: {ecc_enc_time:.4f}s, Decrypt: {ecc_dec_time:.4f}s")
|
||||||
|
|
||||||
|
finally:
|
||||||
|
# Clean up test file
|
||||||
|
if os.path.exists(filename):
|
||||||
|
os.remove(filename)
|
||||||
|
|
||||||
|
print()
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def create_performance_graphs(results):
|
||||||
|
"""Create performance comparison graphs using Bokeh"""
|
||||||
|
output_file("file_transfer_performance.html")
|
||||||
|
|
||||||
|
file_sizes = results['file_sizes']
|
||||||
|
|
||||||
|
# Encryption time comparison
|
||||||
|
p1 = figure(title="Encryption Time Comparison", x_axis_label="File Size (MB)",
|
||||||
|
y_axis_label="Time (seconds)", width=400, height=300)
|
||||||
|
p1.line(file_sizes, results['rsa_encrypt'], legend_label="RSA", line_color="red", line_width=2)
|
||||||
|
p1.circle(file_sizes, results['rsa_encrypt'], color="red", size=6)
|
||||||
|
p1.line(file_sizes, results['ecc_encrypt'], legend_label="ECC", line_color="blue", line_width=2)
|
||||||
|
p1.circle(file_sizes, results['ecc_encrypt'], color="blue", size=6)
|
||||||
|
p1.legend.location = "top_left"
|
||||||
|
|
||||||
|
# Decryption time comparison
|
||||||
|
p2 = figure(title="Decryption Time Comparison", x_axis_label="File Size (MB)",
|
||||||
|
y_axis_label="Time (seconds)", width=400, height=300)
|
||||||
|
p2.line(file_sizes, results['rsa_decrypt'], legend_label="RSA", line_color="red", line_width=2)
|
||||||
|
p2.circle(file_sizes, results['rsa_decrypt'], color="red", size=6)
|
||||||
|
p2.line(file_sizes, results['ecc_decrypt'], legend_label="ECC", line_color="blue", line_width=2)
|
||||||
|
p2.circle(file_sizes, results['ecc_decrypt'], color="blue", size=6)
|
||||||
|
p2.legend.location = "top_left"
|
||||||
|
|
||||||
|
# Key generation comparison
|
||||||
|
p3 = figure(title="Key Generation Time", x_axis_label="Algorithm",
|
||||||
|
y_axis_label="Time (seconds)", width=400, height=300,
|
||||||
|
x_range=["RSA", "ECC"])
|
||||||
|
p3.vbar(x=["RSA", "ECC"], top=[results['rsa_keygen'][0], results['ecc_keygen'][0]],
|
||||||
|
width=0.5, color=["red", "blue"])
|
||||||
|
|
||||||
|
# Key size comparison
|
||||||
|
p4 = figure(title="Key Size Comparison", x_axis_label="Algorithm",
|
||||||
|
y_axis_label="Size (bytes)", width=400, height=300,
|
||||||
|
x_range=["RSA", "ECC"])
|
||||||
|
p4.vbar(x=["RSA", "ECC"], top=[results['rsa_key_size'], results['ecc_key_size']],
|
||||||
|
width=0.5, color=["red", "blue"])
|
||||||
|
|
||||||
|
# Create grid layout
|
||||||
|
grid = gridplot([[p1, p2], [p3, p4]])
|
||||||
|
show(grid)
|
||||||
|
|
||||||
|
|
||||||
|
def print_security_analysis():
|
||||||
|
"""Print security analysis and comparison"""
|
||||||
|
print("\nSecurity Analysis - RSA vs ECC")
|
||||||
|
print("=" * 50)
|
||||||
|
print("RSA (2048-bit):")
|
||||||
|
print(" • Security Level: ~112 bits")
|
||||||
|
print(" • Key Size: Large (2048+ bits)")
|
||||||
|
print(" • Resistance: Integer factorization problem")
|
||||||
|
print(" • Quantum Threat: Vulnerable to Shor's algorithm")
|
||||||
|
print(" • Computational Overhead: High for large keys")
|
||||||
|
print()
|
||||||
|
print("ECC (secp256r1):")
|
||||||
|
print(" • Security Level: ~128 bits")
|
||||||
|
print(" • Key Size: Small (256 bits)")
|
||||||
|
print(" • Resistance: Elliptic curve discrete logarithm problem")
|
||||||
|
print(" • Quantum Threat: Vulnerable to modified Shor's algorithm")
|
||||||
|
print(" • Computational Overhead: Lower than equivalent RSA")
|
||||||
|
print()
|
||||||
|
print("Summary:")
|
||||||
|
print(" • ECC provides equivalent security with smaller keys")
|
||||||
|
print(" • ECC is more efficient for mobile/embedded systems")
|
||||||
|
print(" • RSA is more widely supported and established")
|
||||||
|
print(" • Both require post-quantum alternatives for future security")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Main function to run the file transfer comparison"""
|
||||||
|
file_sizes = [1, 5, 10] # MB
|
||||||
|
|
||||||
|
print("Secure File Transfer System - RSA vs ECC Comparison")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Measure performance
|
||||||
|
results = measure_performance(file_sizes)
|
||||||
|
|
||||||
|
# Create performance graphs
|
||||||
|
create_performance_graphs(results)
|
||||||
|
|
||||||
|
# Print security analysis
|
||||||
|
print_security_analysis()
|
||||||
|
|
||||||
|
print(f"\nPerformance graphs saved to: file_transfer_performance.html")
|
||||||
|
print("Open the HTML file in your browser to view the interactive graphs.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
39
IS/Lab/Lab3/RSA.py
Normal file
39
IS/Lab/Lab3/RSA.py
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
from Crypto.PublicKey import RSA
|
||||||
|
from Crypto.Cipher import PKCS1_OAEP
|
||||||
|
import binascii
|
||||||
|
|
||||||
|
def rsa_keygen(bits=2048):
|
||||||
|
key = RSA.generate(bits)
|
||||||
|
return key
|
||||||
|
|
||||||
|
def rsa_en(ptext, pub_key):
|
||||||
|
cipher = PKCS1_OAEP.new(pub_key)
|
||||||
|
ctext = cipher.encrypt(ptext.encode('utf-8'))
|
||||||
|
return ctext
|
||||||
|
|
||||||
|
def rsa_de(ctext, priv_key):
|
||||||
|
cipher = PKCS1_OAEP.new(priv_key)
|
||||||
|
decrypted = cipher.decrypt(ctext)
|
||||||
|
return decrypted.decode('utf-8')
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Welcome to RSA")
|
||||||
|
ptext = input("Enter plaintext: ")
|
||||||
|
|
||||||
|
# RSA key pair
|
||||||
|
key = rsa_keygen()
|
||||||
|
pub_key = key.publickey()
|
||||||
|
priv_key = key
|
||||||
|
|
||||||
|
print("\nPublic Key (n, e):")
|
||||||
|
print("n =", hex(pub_key.n))
|
||||||
|
print("e =", pub_key.e)
|
||||||
|
|
||||||
|
ctext = rsa_en(ptext, pub_key)
|
||||||
|
print("\nYour ciphertext (hex):", binascii.hexlify(ctext).decode())
|
||||||
|
|
||||||
|
decrypted = rsa_de(ctext, priv_key)
|
||||||
|
print("Your decrypted plaintext:", decrypted)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
61
IS/Lab/Lab4/q1.py
Normal file
61
IS/Lab/Lab4/q1.py
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
# mini_demo.py
|
||||||
|
from Crypto.PublicKey import RSA, ECC
|
||||||
|
from Crypto.Hash import SHA256
|
||||||
|
from Crypto.Cipher import AES
|
||||||
|
from Crypto.Signature import pkcs1_15
|
||||||
|
from Crypto.Random import get_random_bytes as rb
|
||||||
|
|
||||||
|
def gen_role(n):
|
||||||
|
r = RSA.generate(2048)
|
||||||
|
print(f"[keygen] role={n} RSA-2048")
|
||||||
|
return {"name": n, "priv": r.export_key(), "pub": r.publickey().export_key()}
|
||||||
|
|
||||||
|
def ecdh_key():
|
||||||
|
a, b = ECC.generate(curve="P-256"), ECC.generate(curve="P-256")
|
||||||
|
s1 = (b.pointQ * a.d).x.to_bytes(32, "big")
|
||||||
|
s2 = (a.pointQ * b.d).x.to_bytes(32, "big")
|
||||||
|
assert s1 == s2
|
||||||
|
k = SHA256.new(s1).digest()
|
||||||
|
print(f"[ecdh] P-256 shared -> AES key {len(k)*8} bits")
|
||||||
|
return k
|
||||||
|
|
||||||
|
def enc(k, m, aad=b""):
|
||||||
|
n = rb(12); c = AES.new(k, AES.MODE_GCM, nonce=n); c.update(aad)
|
||||||
|
ct, t = c.encrypt_and_digest(m)
|
||||||
|
print(f"[enc] nonce={n.hex()} tag={t.hex()}")
|
||||||
|
return n, ct, t
|
||||||
|
|
||||||
|
def dec(k, n, ct, t, aad=b""):
|
||||||
|
c = AES.new(k, AES.MODE_GCM, nonce=n); c.update(aad)
|
||||||
|
pt = c.decrypt_and_verify(ct, t)
|
||||||
|
print(f"[dec] ok len={len(pt)}")
|
||||||
|
return pt
|
||||||
|
|
||||||
|
def sign(role, msg):
|
||||||
|
h = SHA256.new(msg)
|
||||||
|
sig = pkcs1_15.new(RSA.import_key(role["priv"])).sign(h)
|
||||||
|
print(f"[sign] by {role['name']} siglen={len(sig)}")
|
||||||
|
return sig
|
||||||
|
|
||||||
|
def verify(pub, msg, sig):
|
||||||
|
try:
|
||||||
|
pkcs1_15.new(RSA.import_key(pub)).verify(SHA256.new(msg), sig)
|
||||||
|
print("[verify] signature OK")
|
||||||
|
return True
|
||||||
|
except:
|
||||||
|
print("[verify] signature FAIL")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def demo(s, r, msg):
|
||||||
|
print(f"[demo] {s['name']} -> {r['name']}: {msg}")
|
||||||
|
k = ecdh_key()
|
||||||
|
hdr = f"{s['name']}->{r['name']}".encode()
|
||||||
|
sig = sign(s, hdr)
|
||||||
|
n, ct, t = enc(k, msg.encode(), hdr)
|
||||||
|
assert verify(s["pub"], hdr, sig)
|
||||||
|
pt = dec(k, n, ct, t, hdr).decode()
|
||||||
|
print(f"[result] {pt}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
a, b = gen_role("A"), gen_role("B")
|
||||||
|
demo(a, b, "secret message")
|
49
IS/Lab/Lab4/q2.py
Normal file
49
IS/Lab/Lab4/q2.py
Normal file
|
@ -0,0 +1,49 @@
|
||||||
|
# pip install pycryptodome
|
||||||
|
import time, json
|
||||||
|
from Crypto.Util import number
|
||||||
|
|
||||||
|
log=[]
|
||||||
|
|
||||||
|
def blum_prime(bits): # p ≡ 3 (mod 4)
|
||||||
|
while True:
|
||||||
|
p = number.getPrime(bits)
|
||||||
|
if p % 4 == 3: return p
|
||||||
|
|
||||||
|
def keygen(bits=512, ttl=10):
|
||||||
|
p, q = blum_prime(bits//2), blum_prime(bits//2)
|
||||||
|
k = {"p":p, "q":q, "n":p*q, "exp":time.time()+ttl, "revoked":False}
|
||||||
|
log.append({"t":time.time(), "ev":"KEYGEN", "n":k["n"]}); return k
|
||||||
|
|
||||||
|
def publish(k):
|
||||||
|
log.append({"t":time.time(), "ev":"PUBLISH", "n":k["n"]}); return k["n"]
|
||||||
|
|
||||||
|
def revoke(k):
|
||||||
|
k["revoked"] = True; log.append({"t":time.time(), "ev":"REVOKE"})
|
||||||
|
|
||||||
|
def expired(k): return time.time() > k["exp"]
|
||||||
|
|
||||||
|
def renew(k, ttl=10):
|
||||||
|
revoke(k); k2 = keygen(bits=k["n"].bit_length(), ttl=ttl)
|
||||||
|
log.append({"t":time.time(), "ev":"RENEW"}); return k2
|
||||||
|
|
||||||
|
def enc(m, n): return pow(m, 2, n) # c = m^2 mod n
|
||||||
|
|
||||||
|
def dec(c, k): # return one root via CRT (Rabin has 4 roots)
|
||||||
|
p, q, n = k["p"], k["q"], k["n"]
|
||||||
|
mp, mq = pow(c, (p+1)//4, p), pow(c, (q+1)//4, q)
|
||||||
|
yp, yq = number.inverse(p, q), number.inverse(q, p)
|
||||||
|
return (mp*q*yq + mq*p*yp) % n
|
||||||
|
|
||||||
|
# Demo
|
||||||
|
k = keygen(ttl=2); n = publish(k)
|
||||||
|
m = 123456789
|
||||||
|
c = enc(m, n); m1 = dec(c, k)
|
||||||
|
print("ok:", m == m1)
|
||||||
|
|
||||||
|
time.sleep(2.1) # simulate expiry
|
||||||
|
if expired(k) or k["revoked"]:
|
||||||
|
k = renew(k, ttl=5); n = publish(k)
|
||||||
|
|
||||||
|
c2 = enc(m, n); m2 = dec(c2, k)
|
||||||
|
print("ok2:", m == m2)
|
||||||
|
print(json.dumps(log, indent=2))
|
31
IS/Lab/Lab5/customhash.py
Normal file
31
IS/Lab/Lab5/customhash.py
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
import time
|
||||||
|
|
||||||
|
MASK32 = 0xFFFFFFFF
|
||||||
|
|
||||||
|
def hash_gen(s: str, h: int, mult: int):
|
||||||
|
"""Compute hash of the whole string, print it each loop iteration, repeat."""
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
cur = h & MASK32
|
||||||
|
for ch in s:
|
||||||
|
cur = (cur * mult + ord(ch)) & MASK32
|
||||||
|
cur ^= (cur >> 16)
|
||||||
|
cur = (cur * 0x85ebca6b) & MASK32
|
||||||
|
cur ^= (cur >> 13)
|
||||||
|
print(f"Hash: {cur:#010x}")
|
||||||
|
h = cur
|
||||||
|
time.sleep(2)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\nStopped.")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
hash_init = int(input("Enter initial Hash value: "))
|
||||||
|
hash_mult = int(input("Enter Hash Multiplier: "))
|
||||||
|
|
||||||
|
s = input("Enter String to Hash: ")
|
||||||
|
print("Welcome to the Hash Generator™: ")
|
||||||
|
hash_gen(s, hash_init, hash_mult)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
55
IS/Lab/Lab5/hashbench.py
Normal file
55
IS/Lab/Lab5/hashbench.py
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
import hashlib
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
import time
|
||||||
|
|
||||||
|
def ds_gen(dsize):
|
||||||
|
"""Generate random strings dataset"""
|
||||||
|
dataset = []
|
||||||
|
for _ in range(dsize):
|
||||||
|
length = random.randint(500000, 1000000)
|
||||||
|
random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||||
|
dataset.append(random_string)
|
||||||
|
return dataset
|
||||||
|
|
||||||
|
def hash_benchmark(dataset, hash_func):
|
||||||
|
"""Benchmark hashing function and detect collisions"""
|
||||||
|
start_time = time.time()
|
||||||
|
hashes = {}
|
||||||
|
collisions = []
|
||||||
|
|
||||||
|
for data in dataset:
|
||||||
|
hash_value = hash_func(data.encode()).hexdigest()
|
||||||
|
if hash_value in hashes:
|
||||||
|
collisions.append((data, hashes[hash_value]))
|
||||||
|
else:
|
||||||
|
hashes[hash_value] = data
|
||||||
|
|
||||||
|
end_time = time.time()
|
||||||
|
return end_time - start_time, len(collisions), collisions
|
||||||
|
|
||||||
|
def main():
|
||||||
|
dsize = int(input("Enter data size (50-100): "))
|
||||||
|
dsize = max(50, min(100, dsize)) # Ensure range 50-100
|
||||||
|
|
||||||
|
dataset = ds_gen(dsize)
|
||||||
|
|
||||||
|
hash_functions = [
|
||||||
|
(hashlib.md5, "MD5"),
|
||||||
|
(hashlib.sha1, "SHA-1"),
|
||||||
|
(hashlib.sha256, "SHA-256")
|
||||||
|
]
|
||||||
|
|
||||||
|
print(f"Testing with {len(dataset)} strings\n")
|
||||||
|
|
||||||
|
for hash_func, name in hash_functions:
|
||||||
|
time_taken, collision_count, collisions = hash_benchmark(dataset, hash_func)
|
||||||
|
print(f"{name}:")
|
||||||
|
print(f" Time: {time_taken:.6f} seconds")
|
||||||
|
print(f" Collisions: {collision_count}")
|
||||||
|
if collisions:
|
||||||
|
print(f" Collision pairs: {collisions[:3]}") # Show first 3
|
||||||
|
print()
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
29
IS/Lab/Lab5/socket/clienthash.py
Normal file
29
IS/Lab/Lab5/socket/clienthash.py
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
import socket
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
host = "127.0.0.1"
|
||||||
|
port = 5001
|
||||||
|
|
||||||
|
message = b"hello integrity"
|
||||||
|
tamper = False # change to True to simulate corruption
|
||||||
|
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||||
|
s.connect((host, port))
|
||||||
|
send_data = message if not tamper else message[:-1] + b"X"
|
||||||
|
s.sendall(send_data)
|
||||||
|
|
||||||
|
server_digest = s.recv(128).decode()
|
||||||
|
local_digest = hashlib.sha256(message).hexdigest()
|
||||||
|
|
||||||
|
ok = (server_digest == local_digest)
|
||||||
|
print("server:", server_digest)
|
||||||
|
print("local :", local_digest)
|
||||||
|
print("match :", ok)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
|
|
22
IS/Lab/Lab5/socket/serverhash.py
Normal file
22
IS/Lab/Lab5/socket/serverhash.py
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
import socket
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
host = "127.0.0.1"
|
||||||
|
port = 5001
|
||||||
|
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
|
||||||
|
server.bind((host, port))
|
||||||
|
server.listen(1)
|
||||||
|
conn, addr = server.accept()
|
||||||
|
with conn:
|
||||||
|
data = conn.recv(4096)
|
||||||
|
digest = hashlib.sha256(data).hexdigest()
|
||||||
|
conn.sendall(digest.encode())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
|
|
63
IS/Lab/Lab6/dh_basic.py
Normal file
63
IS/Lab/Lab6/dh_basic.py
Normal file
|
@ -0,0 +1,63 @@
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
from Crypto.Hash import SHA256
|
||||||
|
from Crypto.Protocol.KDF import HKDF
|
||||||
|
|
||||||
|
|
||||||
|
def rfc3526_group14() -> Tuple[int, int]:
|
||||||
|
p_hex = (
|
||||||
|
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
|
||||||
|
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
|
||||||
|
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
|
||||||
|
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
|
||||||
|
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
|
||||||
|
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
|
||||||
|
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
|
||||||
|
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
|
||||||
|
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
|
||||||
|
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
|
||||||
|
"15728E5A8AACAA68FFFFFFFFFFFFFFFF"
|
||||||
|
)
|
||||||
|
return int(p_hex, 16), 2
|
||||||
|
|
||||||
|
|
||||||
|
def int_to_fixed_length_bytes(value: int, length_bits: int) -> bytes:
|
||||||
|
length_bytes = (length_bits + 7) // 8
|
||||||
|
return value.to_bytes(length_bytes, byteorder="big")
|
||||||
|
|
||||||
|
|
||||||
|
def dh_keypair(p: int, g: int, private_bits: int = 256) -> Tuple[int, int]:
|
||||||
|
from Crypto.Util import number
|
||||||
|
|
||||||
|
a = 0
|
||||||
|
while a < 2:
|
||||||
|
a = number.getRandomNBitInteger(private_bits)
|
||||||
|
A = pow(g, a, p)
|
||||||
|
return a, A
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
p, g = rfc3526_group14()
|
||||||
|
a_priv, a_pub = dh_keypair(p, g)
|
||||||
|
b_priv, b_pub = dh_keypair(p, g)
|
||||||
|
|
||||||
|
a_shared = pow(b_pub, a_priv, p)
|
||||||
|
b_shared = pow(a_pub, b_priv, p)
|
||||||
|
same = (a_shared == b_shared)
|
||||||
|
|
||||||
|
print("Lab6: Basic Diffie-Hellman (no symmetric cipher)")
|
||||||
|
print(f"- Group: p({p.bit_length()} bits), g={g}")
|
||||||
|
print(f"- A public: {hex(a_pub)[:18]}...")
|
||||||
|
print(f"- B public: {hex(b_pub)[:18]}...")
|
||||||
|
print(f"- Shared equal: {same}")
|
||||||
|
|
||||||
|
# Optionally derive a fixed-length key material to show post-processing (not used to encrypt)
|
||||||
|
shared_bytes = int_to_fixed_length_bytes(a_shared, p.bit_length())
|
||||||
|
key_material = HKDF(shared_bytes, 32, salt=None, hashmod=SHA256, context=b"demo")
|
||||||
|
print(f"- Derived key material (SHA256/HKDF) prefix: {key_material.hex()[:16]}...")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
|
|
103
IS/Lab/Lab6/elgamal_schnorr.py
Normal file
103
IS/Lab/Lab6/elgamal_schnorr.py
Normal file
|
@ -0,0 +1,103 @@
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
from Crypto.Hash import SHA256
|
||||||
|
from Crypto.Util.number import getPrime
|
||||||
|
|
||||||
|
|
||||||
|
def elgamal_keygen(bits: int = 512) -> Tuple[Tuple[int, int, int], int]:
|
||||||
|
p = getPrime(bits)
|
||||||
|
g = random.randrange(2, p - 1)
|
||||||
|
x = random.randrange(1, p - 1)
|
||||||
|
h = pow(g, x, p)
|
||||||
|
return (p, g, h), x
|
||||||
|
|
||||||
|
def elgamal_encrypt(message: bytes, pub_key: Tuple[int, int, int]) -> Tuple[int, int]:
|
||||||
|
p, g, h = pub_key
|
||||||
|
m = int.from_bytes(message, "big")
|
||||||
|
if m >= p:
|
||||||
|
raise ValueError("Message too large for key size")
|
||||||
|
k = random.randrange(1, p - 1)
|
||||||
|
c1 = pow(g, k, p)
|
||||||
|
s = pow(h, k, p)
|
||||||
|
c2 = (m * s) % p
|
||||||
|
return c1, c2
|
||||||
|
|
||||||
|
|
||||||
|
def elgamal_decrypt(ciphertext: Tuple[int, int], priv_key: int, pub_key: Tuple[int, int, int]) -> bytes:
|
||||||
|
c1, c2 = ciphertext
|
||||||
|
p, _, _ = pub_key
|
||||||
|
s = pow(c1, priv_key, p)
|
||||||
|
s_inv = pow(s, p - 2, p)
|
||||||
|
m = (c2 * s_inv) % p
|
||||||
|
if m == 0:
|
||||||
|
return b""
|
||||||
|
m_len = (m.bit_length() + 7) // 8
|
||||||
|
return m.to_bytes(m_len, "big")
|
||||||
|
|
||||||
|
|
||||||
|
def schnorr_keygen(bits: int = 512) -> Tuple[Tuple[int, int, int], int]:
|
||||||
|
# Use same style group as ElGamal demo for simplicity
|
||||||
|
p = getPrime(bits)
|
||||||
|
g = random.randrange(2, p - 1)
|
||||||
|
x = random.randrange(1, p - 1)
|
||||||
|
y = pow(g, x, p)
|
||||||
|
return (p, g, y), x
|
||||||
|
|
||||||
|
|
||||||
|
def schnorr_sign(message: bytes, priv_key: int, params: Tuple[int, int, int]) -> Tuple[int, int]:
|
||||||
|
p, g, _ = params
|
||||||
|
k = random.randrange(1, p - 1)
|
||||||
|
r = pow(g, k, p)
|
||||||
|
h = SHA256.new()
|
||||||
|
h.update(r.to_bytes((r.bit_length() + 7) // 8 or 1, "big") + message)
|
||||||
|
e = int.from_bytes(h.digest(), "big") % (p - 1)
|
||||||
|
s = (k + e * priv_key) % (p - 1)
|
||||||
|
return e, s
|
||||||
|
|
||||||
|
|
||||||
|
def schnorr_verify(message: bytes, signature: Tuple[int, int], params: Tuple[int, int, int]) -> bool:
|
||||||
|
p, g, y = params
|
||||||
|
e, s = signature
|
||||||
|
# Compute r' = g^s * y^{-e} mod p
|
||||||
|
y_inv_e = pow(y, (p - 1 - e) % (p - 1), p)
|
||||||
|
r_prime = (pow(g, s, p) * y_inv_e) % p
|
||||||
|
h = SHA256.new()
|
||||||
|
h.update(r_prime.to_bytes((r_prime.bit_length() + 7) // 8 or 1, "big") + message)
|
||||||
|
e_prime = int.from_bytes(h.digest(), "big") % (p - 1)
|
||||||
|
return e_prime == e
|
||||||
|
|
||||||
|
|
||||||
|
def demo() -> None:
|
||||||
|
print("Lab6: ElGamal (encrypt/decrypt) and Schnorr (sign/verify) demo")
|
||||||
|
default_msg = os.environ.get("LAB6_MESSAGE", "Test message for Lab6")
|
||||||
|
try:
|
||||||
|
user_msg = input(f"Enter plaintext [{default_msg}]: ").strip()
|
||||||
|
except EOFError:
|
||||||
|
user_msg = ""
|
||||||
|
message = (user_msg or default_msg).encode()
|
||||||
|
|
||||||
|
# ElGamal
|
||||||
|
pub_e, priv_e = elgamal_keygen(512)
|
||||||
|
c1, c2 = elgamal_encrypt(message, pub_e)
|
||||||
|
recovered = elgamal_decrypt((c1, c2), priv_e, pub_e)
|
||||||
|
print("\nElGamal:")
|
||||||
|
print(f"- Public: p({pub_e[0].bit_length()} bits), g, h")
|
||||||
|
print(f"- Ciphertext c1={hex(c1)[:18]}..., c2={hex(c2)[:18]}...")
|
||||||
|
print(f"- Decrypt OK: {recovered == message}")
|
||||||
|
|
||||||
|
# Schnorr
|
||||||
|
pub_s, priv_s = schnorr_keygen(512)
|
||||||
|
sig = schnorr_sign(message, priv_s, pub_s)
|
||||||
|
ok = schnorr_verify(message, sig, pub_s)
|
||||||
|
print("\nSchnorr:")
|
||||||
|
print(f"- Public: p({pub_s[0].bit_length()} bits), g, y")
|
||||||
|
print(f"- Signature e={sig[0]}, s={sig[1]}")
|
||||||
|
print(f"- Verify OK: {ok}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
demo()
|
||||||
|
|
||||||
|
|
49
IS/Lab/Lab6/socket_rsa/client.py
Normal file
49
IS/Lab/Lab6/socket_rsa/client.py
Normal file
|
@ -0,0 +1,49 @@
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
|
||||||
|
from Crypto.PublicKey import RSA
|
||||||
|
from Crypto.Cipher import PKCS1_OAEP
|
||||||
|
|
||||||
|
|
||||||
|
def recv_exact(conn: socket.socket, n: int) -> bytes:
|
||||||
|
buf = b""
|
||||||
|
while len(buf) < n:
|
||||||
|
chunk = conn.recv(n - len(buf))
|
||||||
|
if not chunk:
|
||||||
|
raise ConnectionError("connection closed")
|
||||||
|
buf += chunk
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
host = "127.0.0.1"
|
||||||
|
port = 5003
|
||||||
|
default_msg = os.environ.get("LAB6_MESSAGE", "rsa hello")
|
||||||
|
try:
|
||||||
|
user_msg = input(f"Enter plaintext [{default_msg}]: ").strip()
|
||||||
|
except EOFError:
|
||||||
|
user_msg = ""
|
||||||
|
message = (user_msg or default_msg).encode()
|
||||||
|
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as c:
|
||||||
|
c.connect((host, port))
|
||||||
|
# Receive server public key
|
||||||
|
klen = int.from_bytes(recv_exact(c, 4), "big")
|
||||||
|
kbytes = recv_exact(c, klen)
|
||||||
|
server_pub = RSA.import_key(kbytes)
|
||||||
|
|
||||||
|
# Encrypt message to server
|
||||||
|
cipher = PKCS1_OAEP.new(server_pub)
|
||||||
|
ctext = cipher.encrypt(message)
|
||||||
|
c.sendall(len(ctext).to_bytes(4, "big") + ctext)
|
||||||
|
|
||||||
|
# Receive acknowledgement
|
||||||
|
rlen = int.from_bytes(recv_exact(c, 4), "big")
|
||||||
|
reply = recv_exact(c, rlen)
|
||||||
|
print("server reply:", reply.decode(errors="ignore"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
|
|
43
IS/Lab/Lab6/socket_rsa/server.py
Normal file
43
IS/Lab/Lab6/socket_rsa/server.py
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
import socket
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
from Crypto.PublicKey import RSA
|
||||||
|
from Crypto.Cipher import PKCS1_OAEP
|
||||||
|
|
||||||
|
|
||||||
|
def generate_rsa(bits: int = 2048) -> Tuple[RSA.RsaKey, RSA.RsaKey]:
|
||||||
|
key = RSA.generate(bits)
|
||||||
|
return key.publickey(), key
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
host = "127.0.0.1"
|
||||||
|
port = 5003
|
||||||
|
|
||||||
|
pub, priv = generate_rsa(2048)
|
||||||
|
pub_pem = pub.export_key()
|
||||||
|
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
|
||||||
|
srv.bind((host, port))
|
||||||
|
srv.listen(1)
|
||||||
|
conn, _ = srv.accept()
|
||||||
|
with conn:
|
||||||
|
# Send server public key
|
||||||
|
conn.sendall(len(pub_pem).to_bytes(4, "big") + pub_pem)
|
||||||
|
|
||||||
|
# Receive client's encrypted message
|
||||||
|
clen = int.from_bytes(conn.recv(4), "big")
|
||||||
|
ctext = conn.recv(clen)
|
||||||
|
|
||||||
|
cipher = PKCS1_OAEP.new(priv)
|
||||||
|
msg = cipher.decrypt(ctext)
|
||||||
|
# Respond: encrypt reply with same public (client will not be able to decrypt without its private),
|
||||||
|
# so just echo plaintext length as acknowledgement for demo.
|
||||||
|
reply = f"received:{len(msg)}".encode()
|
||||||
|
conn.sendall(len(reply).to_bytes(4, "big") + reply)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
|
|
10
IS/Lab/schedule.md
Normal file
10
IS/Lab/schedule.md
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
| Date | Event | Details |
|
||||||
|
|------|-------|---------|
|
||||||
|
| 2025-08-12 | Synopsis Submission | - |
|
||||||
|
| 2025-09-02 | Program Check [7M] / Record Submission [7M] | Upto Lab 4 |
|
||||||
|
| 2025-09-23 | Lab Midsem [20M] | Upto Lab 6 |
|
||||||
|
| 2025-10-14 | Project Progress Check [10]/ Second Record Submission [7M] | Upto Lab 8 |
|
||||||
|
| 2025-10-28 | Lab Endsem | - |
|
||||||
|
| 2025-10-2X | Lab Quiz [9] | Date yet to be finalised |
|
||||||
|
| 2025-11-11 | Project Submission | - |
|
||||||
|
|
169
OS/C/Week10/q2.c
169
OS/C/Week10/q2.c
|
@ -0,0 +1,169 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <limits.h> // For INT_MAX
|
||||||
|
|
||||||
|
// Structure to represent a frame and its last used time
|
||||||
|
typedef struct {
|
||||||
|
int page_number;
|
||||||
|
int last_used_time;
|
||||||
|
} Frame;
|
||||||
|
|
||||||
|
// Function to find if a page exists in frames and return its index
|
||||||
|
// Also updates the last_used_time if found
|
||||||
|
int find_page(Frame frames[], int n_frames, int page, int current_time) {
|
||||||
|
for (int i = 0; i < n_frames; i++) {
|
||||||
|
if (frames[i].page_number == page) {
|
||||||
|
frames[i].last_used_time = current_time; // Update time on hit
|
||||||
|
return i; // Page found (Hit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1; // Page not found (Fault)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to find the index of the Least Recently Used (LRU) page
|
||||||
|
int find_lru_index(Frame frames[], int n_frames) {
|
||||||
|
int min_time = INT_MAX;
|
||||||
|
int lru_index = 0;
|
||||||
|
for (int i = 0; i < n_frames; i++) {
|
||||||
|
// Frame must contain a valid page (not -1)
|
||||||
|
if (frames[i].page_number != -1 && frames[i].last_used_time < min_time) {
|
||||||
|
min_time = frames[i].last_used_time;
|
||||||
|
lru_index = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lru_index;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to print the current state of frames
|
||||||
|
void print_frames(Frame frames[], int n_frames) {
|
||||||
|
printf("[");
|
||||||
|
for (int i = 0; i < n_frames; i++) {
|
||||||
|
if (frames[i].page_number == -1) {
|
||||||
|
printf(" - ");
|
||||||
|
} else {
|
||||||
|
printf(" %d ", frames[i].page_number);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("]\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n_frames, n_pages;
|
||||||
|
int *pages = NULL; // Reference string
|
||||||
|
Frame *frames = NULL; // Frames in memory
|
||||||
|
|
||||||
|
int page_faults = 0;
|
||||||
|
int page_hits = 0;
|
||||||
|
int current_time = 0; // Counter to track usage time
|
||||||
|
int frame_idx = 0; // Index for filling empty frames initially
|
||||||
|
|
||||||
|
// 1. Get Inputs
|
||||||
|
printf("Enter the number of frames: ");
|
||||||
|
if (scanf("%d", &n_frames) != 1 || n_frames <= 0) {
|
||||||
|
fprintf(stderr, "Error: Invalid number of frames.\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Enter the number of pages in the reference string: ");
|
||||||
|
if (scanf("%d", &n_pages) != 1 || n_pages <= 0) {
|
||||||
|
fprintf(stderr, "Error: Invalid number of pages.\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Allocate Memory
|
||||||
|
pages = (int *)malloc(n_pages * sizeof(int));
|
||||||
|
if (pages == NULL) {
|
||||||
|
perror("Failed to allocate memory for pages");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
frames = (Frame *)malloc(n_frames * sizeof(Frame));
|
||||||
|
if (frames == NULL) {
|
||||||
|
perror("Failed to allocate memory for frames");
|
||||||
|
free(pages); // Clean up already allocated memory
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Enter the page reference string (space-separated %d integers):\n", n_pages);
|
||||||
|
for (int i = 0; i < n_pages; i++) {
|
||||||
|
if (scanf("%d", &pages[i]) != 1) {
|
||||||
|
fprintf(stderr, "Error reading page reference string.\n");
|
||||||
|
free(pages);
|
||||||
|
free(frames);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Initialize Frames
|
||||||
|
for (int i = 0; i < n_frames; i++) {
|
||||||
|
frames[i].page_number = -1; // -1 indicates empty frame
|
||||||
|
frames[i].last_used_time = -1; // Initialize time
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\n--- LRU Simulation Start ---\n");
|
||||||
|
printf("Frames: %d | Reference String Length: %d\n\n", n_frames, n_pages);
|
||||||
|
|
||||||
|
// 4. Process Page References
|
||||||
|
for (int i = 0; i < n_pages; i++) {
|
||||||
|
current_time++; // Increment time step for each reference
|
||||||
|
int current_page = pages[i];
|
||||||
|
printf("Ref: %d -> ", current_page);
|
||||||
|
|
||||||
|
int found_index = find_page(frames, n_frames, current_page, current_time);
|
||||||
|
|
||||||
|
if (found_index != -1) {
|
||||||
|
// Page Hit
|
||||||
|
page_hits++;
|
||||||
|
printf("Hit ");
|
||||||
|
} else {
|
||||||
|
// Page Fault
|
||||||
|
page_faults++;
|
||||||
|
printf("Fault ");
|
||||||
|
|
||||||
|
// Find a place for the new page
|
||||||
|
int replace_index = -1;
|
||||||
|
|
||||||
|
// Check for an empty frame first
|
||||||
|
for(int k=0; k < n_frames; k++){
|
||||||
|
if(frames[k].page_number == -1){
|
||||||
|
replace_index = k;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (replace_index != -1) {
|
||||||
|
// Use the empty frame
|
||||||
|
frames[replace_index].page_number = current_page;
|
||||||
|
frames[replace_index].last_used_time = current_time;
|
||||||
|
printf("(loaded into empty frame %d) ", replace_index);
|
||||||
|
} else {
|
||||||
|
// No empty frames, find LRU page to replace
|
||||||
|
replace_index = find_lru_index(frames, n_frames);
|
||||||
|
printf("(replaced P%d in frame %d) ", frames[replace_index].page_number, replace_index);
|
||||||
|
frames[replace_index].page_number = current_page;
|
||||||
|
frames[replace_index].last_used_time = current_time;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
print_frames(frames, n_frames); // Show frame status after each step
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Output Results
|
||||||
|
printf("\n--- LRU Simulation End ---\n");
|
||||||
|
printf("Total Page References: %d\n", n_pages);
|
||||||
|
printf("Total Page Hits: %d\n", page_hits);
|
||||||
|
printf("Total Page Faults: %d\n", page_faults);
|
||||||
|
if (n_pages > 0) {
|
||||||
|
printf("Hit Rate: %.2f%%\n", (double)page_hits / n_pages * 100.0);
|
||||||
|
printf("Fault Rate: %.2f%%\n", (double)page_faults / n_pages * 100.0);
|
||||||
|
} else {
|
||||||
|
printf("Hit Rate: N/A\n");
|
||||||
|
printf("Fault Rate: N/A\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 6. Free Memory
|
||||||
|
free(pages);
|
||||||
|
free(frames);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
176
OS/C/Week10/qq1.c
Normal file
176
OS/C/Week10/qq1.c
Normal file
|
@ -0,0 +1,176 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
// Function to check if a page exists in frames
|
||||||
|
bool isPagePresent(int* frames, int num_frames, int page) {
|
||||||
|
for (int i = 0; i < num_frames; i++) {
|
||||||
|
if (frames[i] == page) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// FIFO Page Replacement Algorithm
|
||||||
|
void fifo(int* reference_string, int num_pages, int num_frames) {
|
||||||
|
int* frames = (int*)malloc(num_frames * sizeof(int));
|
||||||
|
int page_faults = 0;
|
||||||
|
int frame_index = 0;
|
||||||
|
|
||||||
|
// Initialize frames with -1 (indicating empty)
|
||||||
|
for (int i = 0; i < num_frames; i++) {
|
||||||
|
frames[i] = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\nFIFO Page Replacement Algorithm:\n");
|
||||||
|
printf("Reference String: ");
|
||||||
|
for (int i = 0; i < num_pages; i++) {
|
||||||
|
printf("%d ", reference_string[i]);
|
||||||
|
}
|
||||||
|
printf("\n\n");
|
||||||
|
|
||||||
|
for (int i = 0; i < num_pages; i++) {
|
||||||
|
printf("Page %d: ", reference_string[i]);
|
||||||
|
|
||||||
|
// Check if page already exists in frames
|
||||||
|
if (!isPagePresent(frames, num_frames, reference_string[i])) {
|
||||||
|
// Replace page at current frame_index
|
||||||
|
frames[frame_index] = reference_string[i];
|
||||||
|
frame_index = (frame_index + 1) % num_frames;
|
||||||
|
page_faults++;
|
||||||
|
|
||||||
|
printf("Page Fault! Frames: ");
|
||||||
|
} else {
|
||||||
|
printf("No Page Fault. Frames: ");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print current state of frames
|
||||||
|
for (int j = 0; j < num_frames; j++) {
|
||||||
|
if (frames[j] == -1) {
|
||||||
|
printf("[ ] ");
|
||||||
|
} else {
|
||||||
|
printf("[%d] ", frames[j]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\nTotal Page Faults (FIFO): %d\n", page_faults);
|
||||||
|
free(frames);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to find index of page that will be used farthest in future
|
||||||
|
int findOptimalPage(int* reference_string, int* frames, int num_frames, int num_pages, int current_position) {
|
||||||
|
int farthest = -1;
|
||||||
|
int index = -1;
|
||||||
|
|
||||||
|
for (int i = 0; i < num_frames; i++) {
|
||||||
|
int j;
|
||||||
|
for (j = current_position + 1; j < num_pages; j++) {
|
||||||
|
if (frames[i] == reference_string[j]) {
|
||||||
|
if (j > farthest) {
|
||||||
|
farthest = j;
|
||||||
|
index = i;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If page is never used in future
|
||||||
|
if (j == num_pages) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If all pages will be used in future, return the one used farthest
|
||||||
|
return (index == -1) ? 0 : index;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optimal Page Replacement Algorithm
|
||||||
|
void optimal(int* reference_string, int num_pages, int num_frames) {
|
||||||
|
int* frames = (int*)malloc(num_frames * sizeof(int));
|
||||||
|
int page_faults = 0;
|
||||||
|
|
||||||
|
// Initialize frames with -1 (indicating empty)
|
||||||
|
for (int i = 0; i < num_frames; i++) {
|
||||||
|
frames[i] = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\nOptimal Page Replacement Algorithm:\n");
|
||||||
|
printf("Reference String: ");
|
||||||
|
for (int i = 0; i < num_pages; i++) {
|
||||||
|
printf("%d ", reference_string[i]);
|
||||||
|
}
|
||||||
|
printf("\n\n");
|
||||||
|
|
||||||
|
for (int i = 0; i < num_pages; i++) {
|
||||||
|
printf("Page %d: ", reference_string[i]);
|
||||||
|
|
||||||
|
// Check if page already exists in frames
|
||||||
|
if (!isPagePresent(frames, num_frames, reference_string[i])) {
|
||||||
|
int free_frame = -1;
|
||||||
|
|
||||||
|
// Check if there's an empty frame
|
||||||
|
for (int j = 0; j < num_frames; j++) {
|
||||||
|
if (frames[j] == -1) {
|
||||||
|
free_frame = j;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (free_frame != -1) {
|
||||||
|
// If empty frame exists, use it
|
||||||
|
frames[free_frame] = reference_string[i];
|
||||||
|
} else {
|
||||||
|
// Find optimal page to replace
|
||||||
|
int replace_index = findOptimalPage(reference_string, frames, num_frames, num_pages, i);
|
||||||
|
frames[replace_index] = reference_string[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
page_faults++;
|
||||||
|
printf("Page Fault! Frames: ");
|
||||||
|
} else {
|
||||||
|
printf("No Page Fault. Frames: ");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print current state of frames
|
||||||
|
for (int j = 0; j < num_frames; j++) {
|
||||||
|
if (frames[j] == -1) {
|
||||||
|
printf("[ ] ");
|
||||||
|
} else {
|
||||||
|
printf("[%d] ", frames[j]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\nTotal Page Faults (Optimal): %d\n", page_faults);
|
||||||
|
free(frames);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int num_pages, num_frames;
|
||||||
|
|
||||||
|
printf("Enter number of frames: ");
|
||||||
|
scanf("%d", &num_frames);
|
||||||
|
|
||||||
|
printf("Enter number of pages in reference string: ");
|
||||||
|
scanf("%d", &num_pages);
|
||||||
|
|
||||||
|
int* reference_string = (int*)malloc(num_pages * sizeof(int));
|
||||||
|
|
||||||
|
printf("Enter the reference string (page numbers):\n");
|
||||||
|
for (int i = 0; i < num_pages; i++) {
|
||||||
|
scanf("%d", &reference_string[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run FIFO algorithm
|
||||||
|
fifo(reference_string, num_pages, num_frames);
|
||||||
|
|
||||||
|
// Run Optimal algorithm
|
||||||
|
optimal(reference_string, num_pages, num_frames);
|
||||||
|
|
||||||
|
free(reference_string);
|
||||||
|
return 0;
|
||||||
|
}
|
201
OS/C/Week11/q1.c
Normal file
201
OS/C/Week11/q1.c
Normal file
|
@ -0,0 +1,201 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <math.h>
|
||||||
|
#define MAX 100
|
||||||
|
|
||||||
|
// Function for SSTF (Shortest Seek Time First)
|
||||||
|
void sstf(int arr[], int n, int head) {
|
||||||
|
int visited[MAX] = {0}, total_seek = 0, current = head;
|
||||||
|
printf("\nSSTF Sequence:\n%d ", current);
|
||||||
|
for (int count = 0; count < n; count++) {
|
||||||
|
int index = -1, minDist = 1e9;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
if (!visited[i]) {
|
||||||
|
int dist = abs(arr[i] - current);
|
||||||
|
if (dist < minDist) {
|
||||||
|
minDist = dist;
|
||||||
|
index = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visited[index] = 1;
|
||||||
|
total_seek += minDist;
|
||||||
|
current = arr[index];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
printf("\nTotal Seek Time: %d\n", total_seek);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function: Bubble sort in ascending order
|
||||||
|
void sortAsc(int arr[], int n) {
|
||||||
|
for (int i = 0; i < n - 1; i++)
|
||||||
|
for (int j = i + 1; j < n; j++)
|
||||||
|
if (arr[i] > arr[j]) {
|
||||||
|
int temp = arr[i];
|
||||||
|
arr[i] = arr[j];
|
||||||
|
arr[j] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function: Bubble sort in descending order
|
||||||
|
void sortDesc(int arr[], int
|
||||||
|
for (int i = 0; i < n - 1; i++)
|
||||||
|
for (int j = i + 1; j < n; j++)
|
||||||
|
if (arr[i] < arr[j]) {
|
||||||
|
int temp = arr[i];
|
||||||
|
arr[i] = arr[j];
|
||||||
|
arr[j] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function for SCAN (Elevator Algorithm)
|
||||||
|
// Assumes movement is towards the left first, then reverses.
|
||||||
|
void scan(int arr[], int n, int head, int disk_size) {
|
||||||
|
int left[MAX], right[MAX], l = 0, r = 0;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
if (arr[i] < head)
|
||||||
|
left[l++] = arr[i];
|
||||||
|
else
|
||||||
|
right[r++] = arr[i];
|
||||||
|
}
|
||||||
|
sortDesc(left, l);
|
||||||
|
sortAsc(right, r);
|
||||||
|
int total_seek = 0, current = head;
|
||||||
|
printf("\nSCAN Sequence:\n%d ", current);
|
||||||
|
// Service left side (moving toward 0)
|
||||||
|
for (int i = 0; i < l; i++) {
|
||||||
|
total_seek += abs(current - left[i]);
|
||||||
|
current = left[i];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
// If not already at 0, move to 0
|
||||||
|
if (current != 0) {
|
||||||
|
total_seek += current;
|
||||||
|
current = 0;
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
// Then service right side (moving right)
|
||||||
|
for (int i = 0; i < r; i++) {
|
||||||
|
total_seek += abs(right[i] - current);
|
||||||
|
current = right[i];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
printf("\nTotal Seek Time: %d\n", total_seek);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function for C-SCAN (Circular SCAN)
|
||||||
|
// Assumes movement to the right; after reaching the end, the head jumps to 0.
|
||||||
|
void cscan(int arr[], int n, int head, int disk_size) {
|
||||||
|
int left[MAX], right[MAX], l = 0, r = 0;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
if (arr[i] < head)
|
||||||
|
left[l++] = arr[i];
|
||||||
|
else
|
||||||
|
right[r++] = arr[i];
|
||||||
|
}
|
||||||
|
sortAsc(left, l);
|
||||||
|
sortAsc(right, r);
|
||||||
|
int total_seek = 0, current = head;
|
||||||
|
printf("\nC-SCAN Sequence:\n%d ", current);
|
||||||
|
// Service requests to the right
|
||||||
|
for (int i = 0; i < r; i++) {
|
||||||
|
total_seek += abs(right[i] - current);
|
||||||
|
current = right[i];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
// Go to the end if not reached
|
||||||
|
if (current != disk_size - 1) {
|
||||||
|
total_seek += abs(disk_size - 1 - current);
|
||||||
|
current = disk_size - 1;
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
// Jump to beginning (simulate wrap-around)
|
||||||
|
total_seek += (disk_size - 1);
|
||||||
|
current = 0;
|
||||||
|
printf("-> %d ", current);
|
||||||
|
// Service the left side
|
||||||
|
for (int i = 0; i < l; i++) {
|
||||||
|
total_seek += abs(left[i] - current);
|
||||||
|
current = left[i];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
printf("\nTotal Seek Time: %d\n", total_seek);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function for C-LOOK
|
||||||
|
// Assumes movement to the right; after the furthest request, it jumps to the smallest request.
|
||||||
|
void clook(int arr[], int n, int head) {
|
||||||
|
int left[MAX], right[MAX], l = 0, r = 0;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
if (arr[i] < head)
|
||||||
|
left[l++] = arr[i];
|
||||||
|
else
|
||||||
|
right[r++] = arr[i];
|
||||||
|
}
|
||||||
|
sortAsc(left, l);
|
||||||
|
sortAsc(right, r);
|
||||||
|
int total_seek = 0, current = head;
|
||||||
|
printf("\nC-LOOK Sequence:\n%d ", current);
|
||||||
|
// Service the right side
|
||||||
|
for (int i = 0; i < r; i++) {
|
||||||
|
total_seek += abs(right[i] - current);
|
||||||
|
current = right[i];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
// Jump to the leftmost request if any exist on the left
|
||||||
|
if (l > 0) {
|
||||||
|
total_seek += abs(current - left[0]);
|
||||||
|
current = left[0];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
for (int i = 1; i < l; i++) {
|
||||||
|
total_seek += abs(left[i] - current);
|
||||||
|
current = left[i];
|
||||||
|
printf("-> %d ", current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("\nTotal Seek Time: %d\n", total_seek);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int choice, n, head, disk_size;
|
||||||
|
int arr[MAX];
|
||||||
|
printf("Menu:\n");
|
||||||
|
printf("1. SSTF\n");
|
||||||
|
printf("2. SCAN\n");
|
||||||
|
printf("3. C-SCAN\n");
|
||||||
|
printf("4. C-LOOK\n");
|
||||||
|
printf("Enter your choice: ");
|
||||||
|
scanf("%d", &choice);
|
||||||
|
|
||||||
|
printf("Enter number of requests: ");
|
||||||
|
scanf("%d", &n);
|
||||||
|
printf("Enter the request queue (space separated): ");
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
scanf("%d", &arr[i]);
|
||||||
|
}
|
||||||
|
printf("Enter initial head position: ");
|
||||||
|
scanf("%d", &head);
|
||||||
|
|
||||||
|
if (ce == 2 || choice == 3) { // SCAN and C-SCAN require the disk size
|
||||||
|
printf("Enter disk size: ");
|
||||||
|
scanf("%d", &disk_size);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (choice) {
|
||||||
|
case 1:
|
||||||
|
sstf(arr, n, head);
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
scan(arr, n, head, disk_size);
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
cscan(arr, n, head, disk_size);
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
clook(arr, n, head);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
printf("Invalid choice!\n");
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
BIN
OS/C/Week11/qq1
Executable file
BIN
OS/C/Week11/qq1
Executable file
Binary file not shown.
11
OS/C/Week11/qq1.c
Normal file
11
OS/C/Week11/qq1.c
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <math.h>
|
||||||
|
#define MAX 100
|
||||||
|
void sstf(int a[],int n,int h){int v[MAX]={0},t=0,c=h;printf("\nSSTF:\n%d ",c);for(int i=0;i<n;i++){int x=-1,m=1e9;for(int j=0;j<n;j++){if(!v[j]){int d=abs(a[j]-c);if(d<m){m=d;x=j;}}}v[x]=1;t+=m;c=a[x];printf("->%d ",c);}printf("\nTotal:%d\n",t);}
|
||||||
|
void sortAsc(int a[],int n){for(int i=0;i<n-1;i++)for(int j=i+1;j<n;j++)if(a[i]>a[j]){int t=a[i];a[i]=a[j];a[j]=t;}}
|
||||||
|
void sortDesc(int a[],int n){for(int i=0;i<n-1;i++)for(int j=i+1;j<n;j++)if(a[i]<a[j]){int t=a[i];a[i]=a[j];a[j]=t;}}
|
||||||
|
void scan(int a[],int n,int h,int d){int l[MAX],r[MAX],x=0,y=0;for(int i=0;i<n;i++)if(a[i]<h)l[x++]=a[i];else r[y++]=a[i];sortDesc(l,x);sortAsc(r,y);int t=0,c=h;printf("\nSCAN:\n%d ",c);for(int i=0;i<x;i++){t+=abs(c-l[i]);c=l[i];printf("->%d ",c);}if(c){t+=c;c=0;printf("->%d ",c);}for(int i=0;i<y;i++){t+=abs(r[i]-c);c=r[i];printf("->%d ",c);}printf("\nTotal:%d\n",t);}
|
||||||
|
void cscan(int a[],int n,int h,int d){int l[MAX],r[MAX],x=0,y=0;for(int i=0;i<n;i++)if(a[i]<h)l[x++]=a[i];else r[y++]=a[i];sortAsc(l,x);sortAsc(r,y);int t=0,c=h;printf("\nCSCAN:\n%d ",c);for(int i=0;i<y;i++){t+=abs(r[i]-c);c=r[i];printf("->%d ",c);}if(c!=d-1){t+=abs(d-1-c);c=d-1;printf("->%d ",c);}t+=d-1;c=0;printf("->%d ",c);for(int i=0;i<x;i++){t+=abs(l[i]-c);c=l[i];printf("->%d ",c);}printf("\nTotal:%d\n",t);}
|
||||||
|
void clook(int a[],int n,int h){int l[MAX],r[MAX],x=0,y=0;for(int i=0;i<n;i++)if(a[i]<h)l[x++]=a[i];else r[y++]=a[i];sortAsc(l,x);sortAsc(r,y);int t=0,c=h;printf("\nCLOOK:\n%d ",c);for(int i=0;i<y;i++){t+=abs(r[i]-c);c=r[i];printf("->%d ",c);}if(x){t+=abs(c-l[0]);c=l[0];printf("->%d ",c);for(int i=1;i<x;i++){t+=abs(l[i]-c);c=l[i];printf("->%d ",c);}}printf("\nTotal:%d\n",t);}
|
||||||
|
int main(){int c,n,h,d,a[MAX];printf("1.SSTF\n2.SCAN\n3.CSCAN\n4.CLOOK\nChoice:");scanf("%d",&c);printf("Requests:");scanf("%d",&n);printf("Queue:");for(int i=0;i<n;i++)scanf("%d",&a[i]);printf("Head:");scanf("%d",&h);if(c==2||c==3){printf("Size:");scanf("%d",&d);}switch(c){case 1:sstf(a,n,h);break;case 2:scan(a,n,h,d);break;case 3:cscan(a,n,h,d);break;case 4:clook(a,n,h);break;default:printf("Invalid\n");}return 0;}
|
0
OS/C/Week11/test.c
Normal file
0
OS/C/Week11/test.c
Normal file
BIN
OS/C/Week12/rtos
Executable file
BIN
OS/C/Week12/rtos
Executable file
Binary file not shown.
52
OS/C/Week12/rtos.c
Normal file
52
OS/C/Week12/rtos.c
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
typedef struct {
|
||||||
|
int id,p,et,re,ad,ta;
|
||||||
|
} Task;
|
||||||
|
|
||||||
|
Task tasks[]={{1,5,2,0,0,0},{2,8,3,0,0,0}};
|
||||||
|
int nt=sizeof(tasks)/sizeof(Task);
|
||||||
|
int st=40;
|
||||||
|
|
||||||
|
void simulate_rm(){
|
||||||
|
printf("--- RM ---\n");
|
||||||
|
for(int i=0;i<nt;i++){tasks[i].re=tasks[i].ad=tasks[i].ta=0;}
|
||||||
|
for(int t=0;t<st;t++){
|
||||||
|
for(int i=0;i<nt;i++){
|
||||||
|
if(!tasks[i].ta){
|
||||||
|
if(tasks[i].re>0)printf("!T%d:Task%d missed!\n",t,tasks[i].id);
|
||||||
|
tasks[i].re=tasks[i].et;
|
||||||
|
tasks[i].ad=t+tasks[i].p;
|
||||||
|
tasks[i].ta=tasks[i].p;
|
||||||
|
}
|
||||||
|
tasks[i].ta--;
|
||||||
|
}
|
||||||
|
int r=-1,hp=10000;
|
||||||
|
for(int i=0;i<nt;i++)
|
||||||
|
if(tasks[i].re>0&&tasks[i].p<hp){hp=tasks[i].p;r=i;}
|
||||||
|
if(r>=0){printf("T%d:Task%d run\n",t,tasks[r].id);tasks[r].re--;}
|
||||||
|
else printf("T%d:Idle\n",t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void simulate_edf(){
|
||||||
|
printf("\n--- EDF ---\n");
|
||||||
|
for(int i=0;i<nt;i++){tasks[i].re=tasks[i].ad=tasks[i].ta=0;}
|
||||||
|
for(int t=0;t<st;t++){
|
||||||
|
for(int i=0;i<nt;i++){
|
||||||
|
if(!tasks[i].ta){
|
||||||
|
if(tasks[i].re>0)printf("!T%d:Task%d missed!\n",t,tasks[i].id);
|
||||||
|
tasks[i].re=tasks[i].et;
|
||||||
|
tasks[i].ad=t+tasks[i].p;
|
||||||
|
tasks[i].ta=tasks[i].p;
|
||||||
|
}
|
||||||
|
tasks[i].ta--;
|
||||||
|
}
|
||||||
|
int r=-1,ed=10000;
|
||||||
|
for(int i=0;i<nt;i++)
|
||||||
|
if(tasks[i].re>0&&tasks[i].ad<ed){ed=tasks[i].ad;r=i;}
|
||||||
|
if(r>=0){printf("T%d:Task%d run\n",t,tasks[r].id);tasks[r].re--;}
|
||||||
|
else printf("T%d:Idle\n",t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(){simulate_rm();simulate_edf();return 0;}
|
81
OS/C/Week9/q1-smol.c
Normal file
81
OS/C/Week9/q1-smol.c
Normal file
|
@ -0,0 +1,81 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
#define BLOCKS 4
|
||||||
|
#define REQUESTS 5
|
||||||
|
|
||||||
|
// Memory configuration
|
||||||
|
int memory[BLOCKS] = {100, 50, 25, 10};
|
||||||
|
int allocated[BLOCKS] = {0, 0, 0, 0};
|
||||||
|
|
||||||
|
// Helper: Reset allocation state
|
||||||
|
void resetAllocation() {
|
||||||
|
for(int i = 0; i < BLOCKS; i++) {
|
||||||
|
allocated[i] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print memory status
|
||||||
|
void printMemory() {
|
||||||
|
printf("\nMemory Status:\n");
|
||||||
|
for(int i = 0; i < BLOCKS; i++) {
|
||||||
|
printf("[Size: %d, %s] -> ", memory[i],
|
||||||
|
allocated[i] ? "Allocated" : "Free");
|
||||||
|
}
|
||||||
|
printf("NULL\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// First Fit allocation
|
||||||
|
void firstFit(int size) {
|
||||||
|
for(int i = 0; i < BLOCKS; i++) {
|
||||||
|
if (!allocated[i] && memory[i] >= size) {
|
||||||
|
allocated[i] = 1;
|
||||||
|
printf("Allocated %d bytes using First Fit\n", size);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("First Fit: No suitable block found for %d bytes\n", size);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best Fit allocation
|
||||||
|
void bestFit(int size) {
|
||||||
|
int best = -1;
|
||||||
|
int bestSize = 999999;
|
||||||
|
|
||||||
|
for(int i = 0; i < BLOCKS; i++) {
|
||||||
|
if(!allocated[i] && memory[i] >= size && memory[i] < bestSize) {
|
||||||
|
bestSize = memory[i];
|
||||||
|
best = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(best != -1) {
|
||||||
|
allocated[best] = 1;
|
||||||
|
printf("Allocated %d bytes using Best Fit\n", size);
|
||||||
|
} else {
|
||||||
|
printf("Best Fit: No suitable block found for %d bytes\n", size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main function: run allocation sequence
|
||||||
|
int main() {
|
||||||
|
int requests[REQUESTS] = {15, 35, 60, 10, 5};
|
||||||
|
|
||||||
|
printf("=== FIRST FIT ===\n");
|
||||||
|
printMemory();
|
||||||
|
for(int i = 0; i < REQUESTS; i++) {
|
||||||
|
firstFit(requests[i]);
|
||||||
|
printMemory();
|
||||||
|
}
|
||||||
|
|
||||||
|
resetAllocation();
|
||||||
|
|
||||||
|
printf("=== BEST FIT ===\n");
|
||||||
|
printMemory();
|
||||||
|
for(int i = 0; i < REQUESTS; i++) {
|
||||||
|
bestFit(requests[i]);
|
||||||
|
printMemory();
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
|
@ -1,8 +1,6 @@
|
||||||
read -p "Enter a number: " num
|
if [[ $# -lt 3 ]]; then
|
||||||
if [[ $num -gt 10 ]]; then
|
echo "Usage: $0 <filename1> <filename2>"
|
||||||
echo "Number is greater than 10"
|
exit 1
|
||||||
elif [[ $num -eq 10 ]]; then
|
|
||||||
echo "Number is exactly 10"
|
|
||||||
else
|
|
||||||
echo "Number is less than 10"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if
|
||||||
|
|
46
OS/endsem/bashq.sh
Normal file
46
OS/endsem/bashq.sh
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Ask for the directory
|
||||||
|
echo "Enter directory path:"
|
||||||
|
read dir
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
echo ""
|
||||||
|
echo "Menu:"
|
||||||
|
echo "1. Convert .txt files to .py in $dir"
|
||||||
|
echo "2. List ownership properties (ls -l) of all files in $dir"
|
||||||
|
echo "3. Count .sh files and subdirectories in $dir"
|
||||||
|
echo "4. Exit"
|
||||||
|
echo -n "Choose an option: "
|
||||||
|
read option
|
||||||
|
|
||||||
|
case $option in
|
||||||
|
1)
|
||||||
|
for file in "$dir"/*.txt; do
|
||||||
|
if [ -f "$file" ]; then
|
||||||
|
new="${file%.txt}.py"
|
||||||
|
mv "$file" "$new"
|
||||||
|
echo "Renamed: $file -> $new"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
;;
|
||||||
|
2)
|
||||||
|
ls -l "$dir"
|
||||||
|
;;
|
||||||
|
3)
|
||||||
|
sh_count=$(ls -1 "$dir"/*.sh 2>/dev/null | wc -l)
|
||||||
|
dir_count=$(ls -d "$dir"/*/ 2>/dev/null | wc -w)
|
||||||
|
echo ".sh file count: $sh_count"
|
||||||
|
echo "Subdirectory count: $dir_count"
|
||||||
|
;;
|
||||||
|
4)
|
||||||
|
echo "Exiting..."
|
||||||
|
break
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Invalid option. Please try again."
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "Bye!"
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue