const std = @import("std"); const alloc = std.heap.page_allocator; const Arr = std.ArrayList; const ArgError = error{ TooManyError, TooFewError, InvalidOperationError }; const MathError = error { ResultNegativeError, ResultFractionError }; fn sum(x: u64, y: u64) u64 { var anded: u64 = x & y; var xored: u64 = x ^ y; while (anded != 0) { const shifted: u64 = anded << 1; anded = shifted & xored; xored = xored ^ shifted; } return xored; } fn subtract(x: u64, y: u32) !u64 { if (y > x) { return MathError.ResultNegativeError; } var diff = x; var carry = y; var borrow: u32 = undefined; while (borrow != 0) { borrow = (~diff) & carry; diff = diff ^ carry; carry = borrow << 1; } return diff; } fn multiply(x: u32, y: u32) u64 { var result: u64 = 0; var a = x; var b = y; while (b != 0) { if ((b & 1) == 1) { result = sum(result, a); } a = a << 1; b = b >> 1; } return result; } fn divide(x: u32, y: u32) !u64 { if (y > x) { return MathError.ResultFractionError; } var result: u64 = 0; var a: u64 = x; const b = y; var diff = subtract(a, b) catch return result; while (diff >= 0) { var shift: u5 = 0; var shifted_diff = subtract(a, (b << 1 << shift)) catch { const one: u64 = 1; result = sum(result, one << shift); a = try subtract(a, b << shift); diff = subtract(a, b) catch return result; }; while (shifted_diff >= 0) { // a - (b << 1 << 0) const one: u64= 1; shift = sum(shift, 1); shifted_diff = subtract(a, (one << 1 << shift)) catch { result = sum(result, one << shift); a = try subtract(a, b << shift); diff = subtract(a, b) catch return result; }; } } return 0; } pub fn main() !void { var args = try std.process.argsWithAllocator(alloc); defer args.deinit(); _ = args.skip(); // Skip Zig call if (args.inner.count < 3) { return ArgError.TooFewError; } else if (args.inner.count > 3) { return ArgError.TooManyError; } var x: u32 = undefined; var y: u32 = undefined; var operation: u2 = undefined; // Iter through args var count: usize = 1; while (args.next()) |arg| { std.debug.print("Arg {d}: {s}\n", .{ count, arg }); if (count == 1) { x = try std.fmt.parseInt(u32, arg, 10); } else if (count == 2) { operation = switch (arg[0]) { '+' => 0, '-' => 1, '*' => 2, '/' => 3, else => return ArgError.InvalidOperationError, }; } else if (count == 3) { y = try std.fmt.parseInt(u32, arg, 10); } count += 1; } var bit_op: u64 = undefined; var norm_op: u64 = undefined; switch (operation) { 0 => blk: { bit_op = sum(x, y); norm_op = x + y; break :blk; }, 1 => blk: { bit_op = try subtract(x, y); norm_op = x - y; break :blk; }, 2 => blk: { bit_op = multiply(x, y); norm_op = x * y; break :blk; }, 3, => blk: { bit_op = try divide(x, y); norm_op = x / y; break :blk; }, } const working = bit_op == norm_op; std.debug.print("Bit Math works? {any} | Normal: {d} | Bizit: {d}\n", .{ working, norm_op, bit_op }); }