c++ - Decimal Division by left shift -


i have been given question convert base 10 2 without using division(/) , modules(%),so came solution of using bitwise and(&)and right shift(>>) operators.

so start learn these 2 operators still questions not find answer or understand logic behind.

if understand correctly division works according digits place value,in decimal , binary both . when divide number 10 or 2 ,we shift place value 1 place right in both ,which result in division 10 in decimal , 2 in binary.

x=120 (in base of ten) if x>>1 have x=12 (division 10)

y=1000 (in base of two) if y>>1 have x=100 (division 2)

but when use piece of code:

#include<iostream> using namespace std ;  int main() {     int a,b=1;     cout <<"enter integer"<<endl;     cin>> a;     cout<<(a & b)<<endl;     a=a>>1;     cout<<a;     cout<<endl;     system("pause");     return 0 ; } 

i comfused cause in mind this

a=120 (in base of ten) if x>>1 have x=12 (division 10)

but result this

a=120 (in base of ten) if x>>1 have x=60 (division 2!!)

i not understand 2 main point result:

first: if operator(>>) shift place value of digits in code , don't change base of number(10) should produce result(12) can see in result of code (which 60).why can see result(60) not 12?

second:if binary left shift (which seems me),does change decimal binary @ first ide or not?

and bitwise , if logical gate(which seems is) :

1.how can put other value except 0 , 1 , steel have answer?

2.according bitwise , rules

y&1=y

then should 120 result of code 1. explanation this?

3.how can generate reminder(according mathematical operations , logic)?

the shift operators in c++ use base 2. is, x >> 1 shifts value x 1 binary digits. note, however, isn't idea shift signed integers value gets unspecified: when playing bit logic, want use unsigned integers, e.g., unsigned int or unsigned long. conversion decimal values internal representation done input operation which, btw, needs checked success:

if (std::cin >> a) {      ... } else {     std::cerr << "error: failed read value a\n"; } 

the other binary operation (& and, | or, ^ _xor, , ~ invert) operate on individual bits. example, 7u & 13u yields 5u. remainder of division power of 2 use and prior division suitable bitmask.

btw, if want better feel of how these guys work in binary, might want play std::bitset<8>: class template has same bitwise operations, can constructed integer, , when printed shows individual bits.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -