Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. contract BitsAndPieces {
  2.  
  3. function and(bytes1 a, bytes1 b) returns (bytes1) {
  4. return a & b;
  5. }
  6.  
  7. function or(bytes1 a, bytes1 b) returns (bytes1) {
  8. return a | b;
  9. }
  10.  
  11. function xor(bytes1 a, bytes1 b) returns (bytes1) {
  12. return a ^ b;
  13. }
  14.  
  15. function negate(bytes1 a) returns (bytes1) {
  16. return a ^ allOnes();
  17. }
  18.  
  19. function shiftLeft(bytes1 a, uint8 n) returns (bytes1) {
  20. var shifted = uint8(a) * 2 ** n;
  21. return bytes1(shifted);
  22. }
  23.  
  24. function shiftRight(bytes1 a, uint8 n) returns (bytes1) {
  25. var shifted = uint8(a) / 2 ** n;
  26. return bytes1(shifted);
  27. }
  28.  
  29. function getFirstN(bytes1 a, uint8 n) returns (bytes1) {
  30. var nOnes = bytes1(2 ** n - 1);
  31. var mask = shiftLeft(nOnes, 8 - n); // Total 8 bits
  32. return a & mask;
  33. }
  34.  
  35. function getLastN(bytes1 a, uint8 n) returns (bytes1) {
  36. var lastN = uint8(a) % 2 ** n;
  37. return bytes1(lastN);
  38. }
  39.  
  40. // Sets all bits to 1
  41. function allOnes() returns (bytes1) {
  42. return bytes1(-1); // 0 - 1, since data type is unsigned, this results in all 1s.
  43. }
  44.  
  45. // Get bit value at position
  46. function getBit(bytes1 a, uint8 n) returns (bool) {
  47. return a & shiftLeft(0x01, n) != 0;
  48. }
  49.  
  50. // Set bit value at position
  51. function setBit(bytes1 a, uint8 n) returns (bytes1) {
  52. return a | shiftLeft(0x01, n);
  53. }
  54.  
  55. // Set the bit into state "false"
  56. function clearBit(bytes1 a, uint8 n) returns (bytes1) {
  57. bytes1 mask = negate(shiftLeft(0x01, n));
  58. return a & mask;
  59. }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement