Guest User

Untitled

a guest
Jan 13th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 1.79 KB | None | 0 0
  1. package com.likella.util
  2.  
  3. import java.math.BigInteger
  4.  
  5. public class BinaryCode {
  6.    
  7.        protected ArrayList<Byte> code
  8.    
  9.        static ArrayList<Byte> hexStringToByteArray(String s) {
  10.           ArrayList<Byte> data = []
  11.           for (i in 0..((s.length()-2)/2)) {
  12.              data << ((Character.digit(s.charAt(i*2), 16) << 4 ) + Character.digit(s.charAt(i*2+1), 16))
  13.           }
  14.           data
  15.        }
  16.    
  17.        static String toHex(ArrayList<Byte> b) {
  18.           String.format("%0" + (b.size() << 1) + "x", new BigInteger(1, (byte[]) b.toArray()))
  19.        }
  20.    
  21.        BinaryCode(){
  22.           code = []
  23.        }
  24.    
  25.        BinaryCode(def s, Integer byteSize=null){
  26.           if(s instanceof String)
  27.              code = hexStringToByteArray(s)
  28.           else if(code instanceof BinaryCode)
  29.              code = s.getCode()
  30.           else
  31.              code = s
  32.    
  33.           if(byteSize){
  34.              if(code.size()<byteSize)
  35.                 (code.size()..(byteSize-1)).each{ code<< 0 }
  36.              if(code.size()>byteSize)
  37.                 code = code[0..(byteSize-1)]
  38.           }
  39.           println code
  40.        }
  41.    
  42.        BinaryCode(BinaryCode b){
  43.           code = b.getCode()
  44.        }
  45.    
  46.        def leftShift(def b){
  47.           def aux = b
  48.           if(b instanceof String)
  49.              aux = b.bytes
  50.           if(b instanceof BinaryCode)
  51.              aux = b.getCode()
  52.           code = [code, aux].flatten()
  53.           this
  54.        }
  55.    
  56.        def encodeAsMD5(){
  57.           code = hexStringToByteArray( ((byte[])code).encodeAsMD5() )
  58.           this
  59.        }
  60.    
  61.        def padTo(int n){
  62.           code = Arrays.copyOf( (byte[])code , n)
  63.           this
  64.        }
  65.    
  66.        String toString(){
  67.           toHex(code)
  68.        }
  69.    
  70.        ArrayList<Byte> getCode(){
  71.           code
  72.        }
  73.    
  74.        def xor(def b){
  75.    
  76.           if(b instanceof String)
  77.           b = b.bytes
  78.           else if (b instanceof BinaryCode)
  79.           b = b.getCode()
  80.    
  81.           if(size()>0){
  82.              for(i in 0..(size()-1)){
  83.                 code[i] = code[i]^b[i]
  84.              }
  85.           }
  86.           this
  87.        }
  88.    
  89.        int size(){
  90.           code.size()
  91.        }
  92.     }
Add Comment
Please, Sign In to add comment