AntonioVillanueva

Transform String -> to Array<UShort> -> to Array <UByte>

Nov 30th, 2021
773
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * Transform  Array<UShort> to Array <UByte>
  3.  * Antonio Villanueva Segura
  4.  */
  5.  
  6. fun main() {
  7.     var str="abcdefg" //Test string array
  8.    
  9.     var arrayUShort=toUShortArray(str) //String to UShort array
  10.     printArrayUShort (arrayUShort)//Show UShort array
  11.    
  12.     var arrayUByte=toUByteArray(arrayUShort)//UShort array to UByte array
  13.     printArray(arrayUByte)//Show UByte array
  14.    
  15. }
  16.  
  17.  
  18. //String ->  Char -> to  UShort
  19. fun toUShortArray(s:String):Array <UShort>{
  20.     var arrayUshort = Array<UShort> (s.length){0U} //Same size like string array
  21.    
  22.     for (i in s.indices){//loop through the  string array
  23.         //arrayUshort[i]=s[i].toShort().toUShort()
  24.         arrayUshort[i]=s[i].code.toUShort()
  25.     }    
  26.     return arrayUshort    
  27. }
  28.  
  29.  
  30. //Transform  UShort array -> UByte array
  31. fun toUByteArray (a:Array<UShort>):Array<UByte>{
  32.    
  33.     var arrayUbyte=Array<UByte> (a.size * 2){0U}//El doble
  34.    
  35.     for (i in a.indices ){
  36.         arrayUbyte[i*2+0]=a[i].toInt().shr(8).toUByte()
  37.         arrayUbyte[i*2+1]=a[i].toUByte()        
  38.     }
  39.     return arrayUbyte    
  40. }
  41.  
  42.  
  43. //Show UByte array
  44. fun printArray(a:Array<UByte>){
  45.     println ("Type = ${(a[0]::class.simpleName)}" )    
  46.     for (e in a){
  47.         println ("0x%02x".format (e.toInt()))
  48.     }
  49. }
  50.  
  51. //Show UByte array
  52. fun printArrayUShort(a:Array<UShort>){
  53.     println ("Type = ${(a[0]::class.simpleName)}" )    
  54.     for (e in a){
  55.         println ("0x%04x".format (e.toInt()))
  56.     }
  57. }
RAW Paste Data