参考
いろいろ
ichigojam basicの世界感では、ビット操作の割り算あたりが
「精鋭」小学生でも難しく、最終章の魔王クラスで
単純になんかいひくが理解できれば良い方(精鋭)
掃き出し法(回復法)、シフトしたのを先に引いて比較して場合により戻すやりかたは、情報系の大学でもムズイ
128ビット浮動小数点は、ちょムズイ(あまり使用されない だから?)
除算器の無いCPUで範囲や精度を絞って高速化したいからやる。
目的
負の数の割り算をシフトで行うときの注意(厳密では、ない ちょつとだいたい)
●負の数の1シフトの場合、全体に+1
単純に-3を算術シフト演算した場合(a,bは、一時変数)
a = (-3)>>1
a は、 -2 (なんかちがう)
b = ((-3)+1)>>1
b は、 -1
もしくは、
b = -3
b++
b>>=1
結果
プログラム
//mainasu_3_sifuto_asobu_UNO_1
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Serial.println();
Serial.println("START");
Serial.println();
}
// the loop routine runs over and over again forever:
void loop() {
char a,b;
a = (-3)>>1;
b = ((-3)+1)>>1;
//b = -3;
//b++;
//b>>=1;
Serial.println((int)a);
Serial.println((int)b);
delay(3000); // delay in between reads for stability
}
おまけ
オンラインコンパイラ
#include <iostream>
using namespace std;
int main(void){
// Your code here!
for(int i=-10;i!=0;i++){
printf("(%d),[%d],<%d>,{%d}\n",i,i>>1,(i+1)>>1,i/2);
}
}
(-10),[-5],<-5>,{-5}
(-9),[-5],<-4>,{-4}
(-8),[-4],<-4>,{-4}
(-7),[-4],<-3>,{-3}
(-6),[-3],<-3>,{-3}
(-5),[-3],<-2>,{-2}
(-4),[-2],<-2>,{-2}
(-3),[-2],<-1>,{-1}
(-2),[-1],<-1>,{-1}
(-1),[-1],<0>,{0}