Guest User

Untitled

a guest
Dec 13th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1.  
  2. /** Represents an array of integers each in the range -8..7.
  3.  *  Such integers may be represented in 4 bits (called nybbles).
  4.  *  @author Naing Ye Aung
  5.  */
  6. public class Nybbles {
  7.     /** Return an array of size N. */
  8.     public Nybbles(int N) {
  9.         // DON'T CHANGE THIS.
  10.         _data = new int[(N + 7) / 8];
  11.         _n = N;
  12.     }
  13.  
  14.     /** Return the size of THIS. */
  15.     public int size() {
  16.         return _n;
  17.     }
  18.  
  19.     /** Return the Kth integer in THIS array, numbering from 0.
  20.      *  Assumes 0 <= K < N. */
  21.     public int get(int k) {
  22.         if (k < 0 || k >= _n) {
  23.             throw new IndexOutOfBoundsException();
  24.         } else {
  25.             return (((_data[(int)(k / 8)] >> ((k - ((k/8) * 8)) * 4)) & ((1 << 4) - 1)) << 28) >> 28;
  26.         }
  27.     }
  28.  
  29.     /** Set the Kth integer in THIS array to VAL.  Assumes
  30.      *  0 <= K < N and -8 <= VAL < 8. */
  31.     public void set(int k, int val) {
  32.         if (k < 0 || k >= _n) {
  33.             throw new IndexOutOfBoundsException();
  34.         } else if (val < -8 || val >= 8) {
  35.             throw new IllegalArgumentException();
  36.         } else {
  37.             _data[(int)(k / 8)] =
  38.                 _data[(int)(k/8)] | (val << ((k - ((k/8) * 8)) * 4));
  39.         }
  40.     }
  41.  
  42.     // DON'T CHANGE OR ADD TO THESE.
  43.     /** Size of current array (in nybbles). */
  44.     private int _n;
  45.     /** The array data, packed 8 nybbles to an int. */
  46.     private int[] _data;
  47. }
Add Comment
Please, Sign In to add comment