Exercises

 

Exercises

  • Write all 16 hexadecimal digits in binary, from memory.

  • Use the sizeof operator in C to find and print the size of ...

  • It is possible to use the XOR operation to swap two variables without requiring an temporary variable. Play around with it, and see if you can figure out how.

 

练习:

  • 根据前面所学的,用二进制表示16位十六进制的数。(tip: 将每位十六进制数分别转换为4位二进制数)
  • 用c语言中的 sizeof 操作(其实  sizeof 不是个函数,但我们一直把它当做函数看,其实它是一个委屈的宏)搞清楚并打印各种类型数据的长度(所占存储空间的大小)!
  • 试用异或(xor)操作交换两个变量而不试用其他临时变量。捯饬一下,看看你能不能搞定它!

用异或交换两个变量,其实很简单,只要记住异或的特性,

设Y为一个二进制的bit位,对于异或(xor)操作则有: Y  xor  0   =  Y  ;   Y  xor  1  = ~Y   (Y的非);   Y  xor   Y  =  0;     ;

现在看一下,两个变量 A 、B交换的情形:

B  =  A  xor  B;       

A  =  A  xor  B;       //   A  =  A  xor  B  =  A  xor   ( A  xor B )  =   A xor  A  xor B  =  (A  xor A)  xor B  =  0  xor B  =  B;  即 A = B;

B =  A  xor  B;       // 此前, B = A  xor  B;    A =  B; 

                               // 那么 B =  A   xor  B     =  B  xor  ( A  xor  B )  =  (A  xor  B )  xor  B  =   A  xor  B  xor  B   = A   xor  (B  xor B )  =  A  xor 0 =  A;     即 B = A;

可见,通过上面三个步骤,就实现了变量A、B的交换;

//  而且都是 A Xor  B 操作, 而且中间语句的左端的变量不同于开始和结束语句的左端的变量,此外,开始和结束语句左端的变量是同一个变量!

 

其实,异或操作是一个非常有用的操作,在密码学中很多加密算法就是用了异或(xor)操作的这些特性来时实现加解密的。 

 

 

 

the original link:http://bottomupcs.sourceforge.net/csbu/x1443.htm

你可能感兴趣的:(加密,算法,解密,存储,语言,variables)