Converting Int64 to Int8

I started using Julia yesterday. My objective to rewrite a data-analysis program written in Python that currently takes more than 24 hours, and cut it down to a few hours.

The first hurdle is the following. From a bitstring (>300bit) I isolate 8-bit in an Int64 variable. The problem is that my 8-bit represents a signed integer. How do I get from the 8-bits in Int64 to Int8 (-128, 127) elegantly and fast? Right now the result ranges (0, 255).

Thanks for any suggestion

A M(inimal) W(orking) E(xample) is always a good start.

julia> UInt8(unsigned(Int64(-20))& 0xff)

I think mod(x, Int8) does what you want.


My first question would be - how are you reading/parsing that bitstring right now? In what form are you reading it in? Intuitively, I’d skip the step with reading it in as a Int64 entirely and directly read a Int8 instead.


I don’t think unsigned does anything here, & treats the data as raw bits anyway. And -20 is already an Int64, as are the data the OP has. So, can just as well write:

julia> UInt8(-20 & 0xff) 

Or, for clarity,

julia> UInt8(-20 & typemax(UInt8)) 

(Edit: BTW, shouldn’t it be turned into an Int8, not an UInt8? I think @cjdoris’s approach is the right one.)

But I agree with @Sukera, it seems suboptimal put the data into an Int64 in the first place.

Another option:

julia> -20 % Int8

julia> typeof(ans)

julia> -20 % UInt8

julia> typeof(ans)

Edit: Didn’t see this was suggested above already.


I agree a minimal working example would help to understand what is really needed… From what I understand you might be looking for

# A Int64 value corresponding to the bits `11111111`
a = 255

# The same 8 bits intrepreted as Int8

Thanks, I see now that unsigned was unnecessary, and I solved the wrong problem because I didn’t read the OP’s problem carefully enough. I did include the redundant Int64 intentionally to show that we were operating on that type because that’s how the OP worded the problem.