80 likes | 164 Views
Working with ‘bits’. Some observations on using x86 bit-manipulations. Twos-complement extension. The following are legal statements in C: They illustrate ‘type promotions’ of signed integers having different storage widths. char c = -5; short s = c; int i = s;. ‘sign-extension’.
E N D
Working with ‘bits’ Some observations on using x86 bit-manipulations
Twos-complement extension • The following are legal statements in C: • They illustrate ‘type promotions’ of signed integers having different storage widths char c = -5; short s = c; int i = s; ‘sign-extension’ 11111111 11111011 11111011 8-bits 16-bits The byte’s sign-bit is replicated throughout in the upper portion of the word
Sign-Extensions • The x86 processor provides some special instructions for integer type-promotions: • CBW: AX sign-extension of AL • CWDE: EAX sign-extension of AX • CDQE: RAX sign-extension of EAX • CWD: DX:AX sign-extension of AX • CDQ: EDX:EAX sign-extension of EAX • CQO: RDX:RAX sign-extension of RDX • movsx sign-extends source to destination • movzx zero-extends source to destination
Absolute value (naïve version) • Here is an amateur’s way of computing |x| in assembly language (test-and-branch): • But jumps flush the CPUs prefetch queue! # # Replaces the signed integer in RAX with its absolute value # abs: cmp $0, %rax # is the value less than zero? jge isok # no, leave value unchanged neg %rax # otherwise negate the value isok: ret # return absolute value in RAX
Absolute value (smart version) • Here is a professional’s way of computing |x| in assembly language (no branching): • No effect on positive integers, but ‘flips the bits and adds one’ for negative integers # # Replaces the signed integer in RAX with its absolute value # abs: cqo # sign-extend RAX to RDX:RAX xor %rdx, %rax # maybe flips all the bits in RAX sub %rdx, %rax # maybe subtracts -1 from RAX ret # return absolute value in RAX
Boolean operations 0 1 & | 0 1 ^ 0 1 ~ 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 1 1 1 1 1 1 0 NOT AND OR XOR Propositional Logic P || Q P && Q !P Assignment Operators P &= Q P |= Q P ^= Q
Examples AND equals OR equals 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 1 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 0 1 0 0 0 1 0 0 1 1 1 0 1 1 0 1
‘squares.s’ • We can compute the ‘square’ of an integer without using any multiplication operations (N+1)2 = N2 + N + N + 1