汇编-加减乘除与或非

以下代码实现C嵌入汇编,实现加减乘除,与或非异或功能

// asm_test.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <stdio.h>
#include <iostream>
using namespace std;
enum {
	ADD,
	SUB,
	MUL,
	DIV,

	AND,
	OR,
	NOT,
	XOR
}ALU;

int calc(int a, int b, int cmd)
{
	if (ADD == cmd) {//加 cmp  dword ptr [cmd],0 ;jne calc+31h
		__asm {
			mov  eax, a;
			mov  eax, dword ptr[a]   ;byte, word, dword,qword
			mov  ecx, b
			add  eax, ecx
		}
	}
	else if (SUB == cmd) {//减
		__asm {
			mov  eax, a
			mov  ecx, b
			sub  eax, ecx
		}
	}
	else if (MUL == cmd) {//乘
		__asm {
			mov  eax, a
			mov  ebx, b
			mul  ebx
		}
	}
	else if (DIV == cmd) {//除
		__asm {
			mov edx, 0 ; 清除被除数高位
			mov eax, a ; 被除数
			mov ecx, b ; 除数
			div ecx
		}
	}
}

int calc2(int a, int b, int cmd)
{
	if (AND == cmd) {//与
		__asm {
			mov  eax, a
			mov  ecx, b
			and  eax, ecx
		}
	}
	else if (OR == cmd) {//或
		__asm {
			mov  eax, a
			mov  ecx, b
			or eax, ecx
		}
	}
	else if (NOT == cmd) {//非
		__asm {
			mov  eax, a
			not eax
		}
	}
	else if (XOR == cmd) {//异或
		__asm {
			mov  eax, a
			mov  ebx, b
			xor  eax, ebx
		}
	}
	else {

	}
	/* Return with result in EAX */
}

 
int main()
{
	//加减乘除
	cout << "4 + 7 = " << calc(4, 7, ADD) << endl;
	cout << "4 - 7 = " << calc(4, 7, SUB) << endl;
	cout << "4 * 7 = " << calc(4, 7, MUL) << endl;
	cout << "8 / 4 = " << calc(8, 4, DIV) << endl;
	//与或非异或
	cout << "and: " << calc2(0b00000111, 0b100000101, AND) << endl;
	cout << "or:  " << calc2(0b00000011, 0b000000101, OR) << endl;
	cout << "not: " << (int)(uint8_t)(calc2(0b10000011, 0, NOT)) << endl;//0b0111_1100 = 0x7C = 124
	cout << "xor: " << calc2(0b00000011, 0b10000001, XOR) << endl;//0b1000_0010 = 0x82 = 130
	return 0;
}

输出如下:在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值