本文介绍了修正了BCD码。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 因为我做了第一次尝试的哈希,并且努力提供 PORTABLE代码来解决问题,我提交此解决方案转换为 以及存储在long中的BCD值。对于 整数和(理论上)字符以及实际上任何整数类型都应该如此。如果它没有, 建议改进它的方法,即使是在显着的速度/代码大小惩罚。 #include< math.h> ; 长bcd(长十进制) { int i; long result = 0; for(i = 0;十进制; ++ i){ 结果+ =(十进制%10)*(int)pow(16 ,i); 十进制/ = 10; } 返回(结果); } 长dec(长bcd) { 长结果= 0; int i; for(i = 0; bcd; ++ i){ result + =(bcd%16)*(int)pow( 10,i); bcd / = 16; } 返回(结果); } / *在一台机器上测试代码,但理论上C是可移植的。 * / Cause I made such a hash of my first attempt, and in an effort to providePORTABLE code to solve the problem, I submit this solution to convert toand from BCD values stored in longs. This should work just as well forints and (in theory) chars and, indeed, any integral type. If it doesn''t,suggest ways to improve it, even at a significant speed/code size penalty. #include <math.h> long bcd(long decimal){int i;long result = 0; for(i = 0; decimal; ++i) {result += (decimal % 10) * (int) pow(16,i);decimal /= 10;} return(result);} long dec(long bcd){long result = 0;int i; for(i = 0; bcd; ++i) {result += (bcd % 16) * (int) pow(10,i);bcd /= 16;} return(result);} /* Code tested on all of one machine, but C is portable in theory. */ 推荐答案 只有当你没有对标准的实现定义 部分做出假设时。 - Brett Only when you don''t make assumptions about implementation-definedportions of the standard. -- Brett pow(16,i)返回一个double,然后将其转换为int。没有保证要么具有长的精度。相反:结果+ =(十进制%10)<< (4 * i); pow(16, i) returns a double, which you then cast to an int. There is no guarantee that either has as much precision as a long. Instead: result += (decimal %10) << (4 * i); 啊,但这些转换是否可以移植到那些使用,例如,倍数为的三倍的机器上字的大小?我的倍数会增加吗? 我无法想象BCD如何在八进制系统中运行(你只需要b / b 就有三位编码每个数字*),或假设三元 系统(/好/ C代码应该是可移植的)。 是问题本身仅限于某些类型的系统? *三位只能给你八个数字。 9位是8 + 1,为您提供编码一个'传统''BCD数字的可能性,可以选择 符号位。你可以从那里做数学。 Ah, but will the shifts be portable to machines that use, say, multiplesof three for their word-size? Will my multiplies? I can''t think of how BCD would work in an octal system (where you''d onlyhave three bits to encode each digit*), or on a hypothetical ternarysystem (which /good/ C code is supposed to be portable to). Is the problem itself limited to certain kinds of systems? *Three bits only gives you eight numbers. Nine bits is 8+1, giving you thepossibility of encoding one `traditional'' BCD digit with the option of asign bit. You can do the math from there. 只有当你没有对标准的实现定义的部分做出假设时。 Only when you don''t make assumptions about implementation-defined portions of the standard. Touche''。 Touche''. 这篇关于修正了BCD码。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-23 17:21