# Converting Int64 to Int8

Hello,
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)
0xec
``````
2 Likes

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

2 Likes

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.

4 Likes

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)
0xec
``````

Or, for clarity,

``````julia> UInt8(-20 & typemax(UInt8))
0xec
``````

(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
-20

julia> typeof(ans)
Int8

julia> -20 % UInt8
0xec

julia> typeof(ans)
UInt8
``````

Edit: Didnâ€™t see this was suggested above already.

3 Likes

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
signed(UInt8(a))
``````

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.