Skip to main content
edited tags; edited tags
Link
Became Hot Network Question
Tweeted twitter.com/StackMma/status/1388870922052980746
Headline typo corrected
Link
Tschibi
  • 877
  • 4
  • 14

Convert bytaArrayByteArray to integer and real valusvalues

Source Link
Tschibi
  • 877
  • 4
  • 14

Convert bytaArray to integer and real valus

during the import of a complex file format I handle ByteArray or lists of byte values. While I can easy transform them from one type to each other:

ba=ByteArray[{1,2,3,4,5,6}];
Normal[ba]

I have problems taking specific bytes of my list and converting them according a given number format e.g. Integer8, Integer32 or Real32.

Normal@ba[[1;;2]] (*Shall interpretet as Integer16*)
Normal@ba[[3;;6]] (*Shall interpretet as Real32*)

Is there an internal and elegant way to do so?

I wrote a workaround for Integer numbers like below but I would guess an internal solution will be way more efficient ...

ByteToInteger[byteArray_,LSBStart_:True,bitSize_:16,signed_:False] :=
    Module[{i,array=byteArray,value=0}, 

        (*Reverse for LSB*)
        If[LSBStart==False,
           array=Reverse[array];
        ];
        
        array=PadLeft[array,bitSize]

        
        (*calculate Unsigned value*)
        value=array[[1]];
        For[i=2,i<=Length@array,i++,
            value=value+array[[i]]*256^(i-1)
        ];
        
        (*adapt to signed if needed*)
        If[signed==True&&value>=2^(bitSize-1),
            value=-(2^bitSize-(value-2^(bitSize-1)))
        ];
        
        value  
    ]

I am open to any suggestions ...