Reputation: 3474
In Python/NumPy, I can convert arrays of ints to arrays of characters quite easily. How can I do this in Julia?
For example in Python:
In [6]: np.array(["A", "T", "C"]).view(np.int32)
Out[6]: array([65, 84, 67], dtype=int32)
And vice versa
In [15]: np.array([65, 84, 67]).view("S8")
Out[15]:
array([b'A', b'T', b'C'],
dtype='|S8')
Upvotes: 1
Views: 774
Reputation: 2131
use Char
and Int
:
Char(120) # = 'x'
Int('x') # = 120
A more complete answer:
ints = [65, 84, 67]
chars = map(Char, ints)
and
chars = ['A', 'T', 'C']
ints = map(Int, chars)
notice that characters and strings are of different types in Julia, see http://docs.julialang.org/en/latest/manual/strings/#characters
EDIT:
You can also use the constructors Char
and Int
:
Char[65, 84, 67]
Int['A', 'T', 'C']
Upvotes: 2
Reputation: 18217
For a more instantaneous conversion, you can use ASCIIString
s and UInt8
arrays. Char
s take four bytes of memory and don't use the compact one byte representation. The code will be:
# chars in s1 to ints in v1
s1 = ASCIIString("ATC")
v1 = s.data
# ints in v2 to chars in s2
v2 = UInt8[65,66,67]
s2 = ASCIIString(v)
In both cases, the same memory is backing both variables, meaning the operation is "instantaneous" but changing one variable would change the other.
Upvotes: 1
Reputation: 114781
Take a look at reinterpret
:
julia> a = ['A' 'T' 'C']
1x3 Array{Char,2}:
'A' 'T' 'C'
julia> b = reinterpret(Int32, a)
1x3 Array{Int32,2}:
65 84 67
That makes a
and b
view the same memory, like a numpy "view". For example, if I change an element of a
:
julia> a[1] = 'Z'
'Z'
b
is also changed:
julia> b
1x3 Array{Int32,2}:
90 84 67
Upvotes: 4