performanceoptimizationtype-conversionjulia

In Julia, how to convert a unsigned number to a signed number like in C?


suppose i have a number 0x83, if it is a unsigned, it will be 131, or if it is a signed number, it will be -125. It is very easy in C that i can just write s8(0x83) to convert it to -125, cause the number is 0x83, it just explain the number. but in Julia, it is different, the UInt8 type can not convert to Int8 easily, I should first judge if it in the Int8's range, and then convert it, otherwise i will use the Int16 type to help. So, how can i do the convertion efficiently and in high performance?


Solution

  • julia> reinterpret(Int8, 0x83)
    -125
    

    This is fast and non-allocating:

    julia> @btime reinterpret(Int8, 0x83)
      1.200 ns (0 allocations: 0 bytes)
    -125
    
    

    This works also on byte sequences, in this case most effort is to allocate the new vector:

    julia> @btime reinterpret(Int8, [0x83, 0x84, 0x85, 0x86, 0x87, 0x88])
      21.206 ns (1 allocation: 64 bytes)
    6-element reinterpret(Int8, ::Vector{UInt8}):
     -125
     -124
     -123
     -122
     -121
     -120