代码求解释与答疑
如题,针对以下问题,一位高人给出以下答案,可惜我笨拙,看懂一小半,
1、请哪位高人给代码解释或注释一下
2、另外,len的最终值为6,但是在在 len = GetBitLen(b); if(GetBitLen(a)>GetBitLen(b)){..}中间加入
cout<<len<<endl;后,len值改变,实在不知道哪的原因;按说是不会变的。
3、代码如下:
- C/C++ code
//---------------------------------------#include <vcl.h>#include <io>#include <stdio.h>#include <iostream>using namespace std;#pragma hdrstop//---------------------------------------#pragma argsused/*---------- 目的线性八叉树求解morton码: X=x1 x2 x3.. Y=y1 y2 y3.. Z=z1 z2 z3.. //x1 x2 x3 y1 y2...z3..为0 or 1 二进制码 通过位操作,实现: M=z1y1x1z2y2x2z3y3x3,并转化为10进制,求解Morron 程序运行结果: 计算出来的结果也对 X=17 010001B Y=21 010101B Z=34 100010B M = 143523 100011000010100011B 从下往上拼起来的 */int GetBitLen(short i){ short len; short stemp; stemp = i; while( stemp && 0xFFFF) { len++; stemp = stemp>>1; } return len;} int GetMorTon1(short int a,short int b,short int c) { short len = 0; int temp = 0; int M = 0; len = GetBitLen(b); if(GetBitLen(a)>GetBitLen(b)) { len = GetBitLen(a); } if(len<GetBitLen(c)) { len = GetBitLen(c); } M = a&0x01 | (b&0x01)<<1 | (c&0x01)<< 2; for(int i =1; i<len; i++) { a = a>>1; b = b>>1; c = c>>1; temp = a&0x01 | (b&0x01)<<1 | (c&0x01)<< 2; M = temp << (3*i) | M; } return M; }int main(int argc, char* argv[]){ short a = 17; short b = 21; short c = 34; printf("%d\n",GetMorTon1(a,b,c)); getchar(); return 0;}//---------------------------------------
[解决办法]
int GetBitLen(short i)
{
short len;
...
...
len++;
len 没有初始化,就直接使用了,能得到6算你运气好,不是6也很正常