0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Julia で配列キャスト

0
Posted at

C言語での配列のキャスト

C言語ではある型の配列を、別の型にキャストすることでアクセスすることができるようになる。

double a[] = {1.0, 2.0};
unsigned char *p = (unsigned char *)a;

for (int i = 0; i < sizeof(double) * 2; i++){
    printf("%02x ", *(p + i));
}
printf("\n");
00 00 00 00 00 00 f0 3f 00 00 00 00 00 00 00 40 

Juliaでもできる

これがJuliaでも同様にできる。reinterpretを用いる。

using Printf

a = [1.0, 2.0]

p = reinterpret(UInt8, a)
for i in 1:sizeof(a)
    @printf("%02x ", p[i])
end
println()
00 00 00 00 00 00 f0 3f 00 00 00 00 00 00 00 40 

reinterpretされたものは通常のベクタではなく、特殊な型になっている。

julia> typeof(p)
Base.ReinterpretArray{UInt8, 1, Float64, Vector{Float64}, false}

データがコピーされているのかと思ったがそうではなく、同じ領域を参照しているようだ。
キャスト後のpを変更するともとの配列に反映される。

julia> p[6] = 10
10
julia> a
2-element Vector{Float64}:
 1.00244140625
 2.0

こんな事ができるとは。さすがJulia。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?