Chinaunix首页 | 论坛 | 博客
  • 博客访问: 571303
  • 博文数量: 141
  • 博客积分: 3425
  • 博客等级: 中校
  • 技术积分: 1609
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-23 15:55
文章分类

全部博文(141)

文章存档

2019年(5)

2011年(19)

2010年(36)

2009年(13)

2008年(50)

2007年(18)

分类: C/C++

2007-10-16 20:54:26

1:
指针类型变量的大小与long类型变量的大小一致。
在32位的系统中,int类型变量和long类型的变量的大小是一样的,所以你在整型变量和指针变量之间做转换是正确的。但是当你的代码面向64位系统时,你的做法是错误的。所以,当你需要时,在指针类型与long类型之间转换。
2:
一个整数乘或者除2的n次幂就是右移或者左移n位。
上面的说法对无符号数和有符号数的乘法来说是正确的;
但是对有符号数的除法来说,是错误的。
int a = -1;
int c = a >> 1; // c == -1
int d = a / 2; // d == 0
对无符号的整型来说,用移位来代替乘或除2的幂是无误的,
这也是尽量使用无符号数的原因之一。
3:
取一个无符号整数数对一个2的幂的余数时,可以使用位运算:
ulong a = b % 32; // == b & (32-1)
4:
在二进制补码中,0不是唯一的与它的相反数相等的数(最大的负数也有此性质)。因此在这样的语句if (x<0) x=-x;后认为x是正数是错误的。
5:
在使用移位操作时应注意,C标准中并没有定义大于(BITS_PER_LONG-1)的移位操作。
6:
检查a和b中至少有一个表达式为零可以用:if (!(a&&b)),这对正整数和负整数均有效。
检查两个表达式均为零可用:if ((a|b)==0),这可以推广到多个表达式:if ((a|b|c|..|z==0))。
检查两个表达式中只有一个为零时可用:if ((!a)^(!b))。
7:
不用临时变量交换两个变量的经典技巧:
a ^= b;
b ^= a;
a ^= b;
8:
对某一位操作的函数:
(Following the spirit of the C language there is no check whether the indices used are out of bounds. That is,if any index is greater or equal BITS_PER_LONG, the result is undefined.)

inline ulong test_bit(ulong a, ulong i)
// Return zero if bit[i] is zero,
// else return one-bit word with bit[i] set.
{
return (a & (1UL << i));
}
The following version returns either zero or one:
static inline bool test_bit01(ulong a, ulong i)
// Return whether bit[i] is set.
{
return ( 0 != test_bit(a, i) );
}
inline ulong set_bit(ulong a, ulong i)
// Return a with bit[i] set.
{
return (a | (1UL << i));
}
inline ulong delete_bit(ulong a, ulong i)
// Return a with bit[i] cleared.
{
return (a & ~(1UL << i));
}
inline ulong change_bit(ulong a, ulong i)
// Return a with bit[i] changed.
{
return (a ^ (1UL << i));
}

阅读(843) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~