From aa390776b26d794ab37aa13833fa7043aad16504 Mon Sep 17 00:00:00 2001 From: iximeow Date: Sun, 23 Nov 2014 03:09:27 -0800 Subject: Add in code for challenge 3 --- src/utils/ConversionUtils.scala | 54 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 3 deletions(-) (limited to 'src/utils/ConversionUtils.scala') diff --git a/src/utils/ConversionUtils.scala b/src/utils/ConversionUtils.scala index 26f2d24..09f3aab 100644 --- a/src/utils/ConversionUtils.scala +++ b/src/utils/ConversionUtils.scala @@ -1,10 +1,10 @@ package ixee.cryptopals.utils -import ByteUtils.WithBitOpts +import ByteUtils._ object ConversionUtils { - def hexStr2Bytes(s: String): Iterator[Byte] = - padToByte(s).grouped(2).map(byteStr2Byte) + def hexStr2Bytes(s: String): Seq[Byte] = + padToByte(s).grouped(2).map(byteStr2Byte).toSeq def byteStr2Byte(str: String): Byte = charSeq2Byte(str.toSeq) @@ -34,5 +34,53 @@ object ConversionUtils { hexStr2Bytes(s).toArray.toBase64 } + + implicit class RichSeqByte(seq: Seq[Byte]) { + def to[T : SizedNumeric : BitOps]: T = { + val numeric = implicitly[SizedNumeric[T]] + if(seq.length < numeric.byteSize) { + throw new RuntimeException("Byte input is not long enough") + } + + var out: Long = seq(0) + for(i <- 1 until numeric.byteSize) { + out << 8 + out = seq(i) | out + } + numeric.fromLong(out) + } + + def hex: String = + seq.map(_.hex).reduceLeft(_ + _) + + def asAscii: String = + new String(seq.toArray) + } + + implicit class RichStringBytes(s: String) { + def asBytes = s.toSeq.map(_.toByte) + } + + // Because doing (_ f _).tupled confuses the inferencer... + def tup[A, B, C](f: (A, B) => C): ((A, B)) => C = f.tupled + + // TODO: tailrec this, get rid of for + def toByteSeq[T : SizedNumeric : BitOps](x: T): Seq[Byte] = { + val buf = new Array[Byte](x.byteSize) + for(i <- 0 until x.byteSize) { + val shiftAmount = (x.byteSize - i - 1) << 3 + buf(i) = (x @>>> shiftAmount).truncatedTo[Byte] + } + buf.toSeq + } + + def toBinaryString[T : SizedNumeric](x: T)(implicit a: BitOps[T]): String = { + val buf = new StringBuilder(x.bitSize) + for(i <- 0 until x.bitSize) { + val shiftAmount: Int = x.bitSize - i - 1 + buf.append((x @>>> shiftAmount) @& 0x01.liftedTo[T]) + } + buf.toString() + } } -- cgit v1.1