#include <stdint.h>

#include "bit_op.h"

/// 通过在bit_array上进行位运算从而实现加法 /// 该函数输入两个8位的bit_array, 返回一个8位的bit_array /// /// 提示: /// - 你可以使用get_bit_8(ba, idx)从给定bit_array中取出第idx位 /// - 你可以使用set_bit_8(ba, idx, bit)ba中第idx位配置为bit值 // 注意: bit_array中第i位是指从低到高第i有效位 ba8_t ba8_add(ba8_t a, ba8_t b) { ba8_t res; uint8_t carry = 0; // 进位标志 for (int i = 0; i < 8; ++i) { // 按位加上a和b uint8_t sum = get_bit_8(a, i) + get_bit_8(b, i) + carry; // 如果和为2或3,则需要进位 if (sum == 2 || sum == 3) { carry = 1; } else { carry = 0; } // 取和的低位 set_bit_8(res, i, sum & 1); } return res; }

// 请使用按位取反(ba_not)和加法(ba_add)实现求一个数的相反数 // 即,给定一个8位补码表示的数字x,求 -x 的8位补码表示 // 提示: 你可以使用int_to_ba_8函数获得常数1的bit_array表示 // ba8_t ba8_negate(ba8_t a) { // 先按位取反 ba8_t not_a = ba_not(a); // 然后加1 ba8_t one = int_to_ba_8(1); ba8_t res = ba8_add(not_a, one); return res; }

// 请使用按位取反(ba_not)和加法(ba_add)实现两个数的减法 // 提示: 你可以使用int_to_ba_8函数获得常数1的bit_array表示 ba8_t ba8_sub(ba8_t a, ba8_t b) { // 求b的相反数 ba8_t neg_b = ba8_negate(b); // 然后将a和-b相加 ba8_t res = ba8_add(a, neg_b); return res; }

8位二进制数组的加法、取反和减法实现

原文地址: https://www.cveoy.top/t/topic/nBk3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录