AntonioVillanueva

Function to transform Array<UShort 16bits > into Array <UByte 8bits>

Nov 25th, 2021 (edited)
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.46 KB | None | 0 0
  1. /*
  2.  * Function to transform Array<UShort 16bits > into Array <UByte 8bits>
  3.  * with generic show function Array ..showArray (array:Array<*>)
  4.  * Antonio Villanueva Segura
  5.  */
  6.  
  7. fun main() {
  8.     //I declare an example Array of unsigned short, Array<UShort>
  9.     var ushortArray=arrayOf<UShort>(0x0102U,0x0304U,0x0506U,0x0708U,0x090AU)
  10.     var ubyteArray =toUByteArray(ushortArray) //Conversion UShortArray to UByteArray
  11.  
  12. }
  13.  
  14. /*Function to show an array in hexadecimal */
  15. fun showArray(array: Array<*>){
  16.     println ("${array[0]!!::class.simpleName}")//Analysis of the type of variable
  17.    
  18.     for (indice in array.indices){//Go through the Array Indices
  19.         print ("["+indice+"]=")
  20.         println ( "0x%x".format  (((array[indice] ).toString()).toInt()))
  21.     }
  22. }
  23.  
  24.  
  25. /* Function to transform Array<UShort> in Array<UByte> ..Receive an UShortArray retuns UByteArray*/
  26. fun toUByteArray(ushortArray:Array<UShort>):Array<UByte>{
  27.    
  28.     //Initialize a UByte(8) Array to the size of UShort(16) Array * 2
  29.     var ubyteArray=Array<UByte>(ushortArray.size * 2){0U}
  30.    
  31.     var index=0
  32.     for (elem in ushortArray){//Walk through the UShort array
  33.         //recovers elem 16bits for write two bytes in Array<UByte>
  34.         ubyteArray[index++]= (elem.toInt().shr(8)).toUByte()  
  35.         ubyteArray[index++]= elem.toUByte()
  36.     }
  37.    
  38.     showArray(ushortArray) //Debug show Array<UShort>
  39.     showArray(ubyteArray) //Debug show Array<UByte>
  40.     return ubyteArray
  41. }
Add Comment
Please, Sign In to add comment