Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Conversion Array<UShort> to Array<UByte>
- * Antonio Villanueva Segura
- */
- fun main() {
- var msg="abcdefg" //String
- var msg1=msg.encodeToByteArray().toTypedArray() //Conversion to ByteArray
- ToShort(msg1)
- }
- /*Byte Short conversion function */
- fun ToShort(array:Array<Byte>){
- //Initialize an array variable of UByte
- var ubyteA= UByteArray(array.size)
- // var ushortA=UShortArray((array.size) / 2)
- var ushortA=Array<UShort>((array.size) / 2){0U}
- var ushort:UShort //HL
- //Conversion Byte to UByte
- for (index in array.indices){
- ubyteA[index]=array[index].toUByte()
- }
- //Conversion UByte Short
- for (index in ushortA.indices){
- ushortA[index] = ubyteA[index*2].toInt().shl(8).toUShort()
- ushortA[index] = ubyteA[index*2+1].toInt().toUShort() or ushortA[index]
- }
- for (n in array){//Debug show Byte Array
- println ("0x%x".format(n.toInt()))
- }
- for (n in ushortA){//Debug show UShort Array
- println ("0x%x".format(n.toInt()))
- }
- }
- //String to UShortArray
- fun toUShortArray(s:String):Array<UShort>{
- var s2=s.encodeToByteArray().toTypedArray() //Conversion to ByteArray
- var s3=Array<UByte>(s2.size){0U} //UByte Array
- var s4=Array<UShort>(s2.size / 2 ){0U} //UShort Array
- //Initialize UByte array
- for (index in s2.indices){
- s3[index]=s2[index].toUByte() //Conversion Byte -> UByte
- }
- //Initialize UShort array
- for (index in s4.indices){
- s4[index]=s3[ index*2 + 0 ].toInt().shl(8).toUShort() //LOW
- s4[index]=s3[ index*2 + 1 ].toUShort() or s4[index] //High
- }
- //Show UShort 16bits Array
- for (elem in s4){
- println ("0x%X".format(elem.toInt()))
- }
- return s4
- }
Add Comment
Please, Sign In to add comment