Function shr [src]

Shifts right. Overflowed bits are truncated. A negative shift amount results in a left shift.

Prototype

pub fn shr(comptime T: type, a: T, shift_amt: anytype) T

Parameters

T: typea: T

Example

test shr { try testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111); try testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0); try testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0); try testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100); try testing.expect(shr(u8, 0b11111111, 3) == 0b00011111); try testing.expect(shr(u8, 0b11111111, 8) == 0); try testing.expect(shr(u8, 0b11111111, 9) == 0); try testing.expect(shr(u8, 0b11111111, -2) == 0b11111100); try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) >> 1); try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) << 1); try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0); try testing.expect(shr(i8, -1, -100) == 0); try testing.expect(shr(i8, -1, 100) == -1); if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest; try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ 0, 0 })); try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ -1, 0 })); }

Source

pub fn shr(comptime T: type, a: T, shift_amt: anytype) T { const is_shl = shift_amt < 0; const abs_shift_amt = @abs(shift_amt); const casted_shift_amt = casted_shift_amt: switch (@typeInfo(T)) { .int => |info| { if (abs_shift_amt < info.bits) break :casted_shift_amt @as( Log2Int(T), @intCast(abs_shift_amt), ); if (info.signedness == .unsigned or is_shl) return 0; return a >> (info.bits - 1); }, .vector => |info| { const Child = info.child; const child_info = @typeInfo(Child).int; if (abs_shift_amt < child_info.bits) break :casted_shift_amt @as( @Vector(info.len, Log2Int(Child)), @splat(@as(Log2Int(Child), @intCast(abs_shift_amt))), ); if (child_info.signedness == .unsigned or is_shl) return @splat(0); return a >> @splat(child_info.bits - 1); }, else => comptime unreachable, }; return if (is_shl) a << casted_shift_amt else a >> casted_shift_amt; }