DEV Community

edo1z
edo1z

Posted on

2 1

Solidityの数値の明示的な型変換の仕様をRustで試してみた

Solidityのドキュメントのここに書いてある内容について、Rustも同じ仕様なのか?などを試してみました。

マイナスのintをuintに変換する

let a:i8 = -3;
println!("a:{}", a as u8);
Enter fullscreen mode Exit fullscreen mode

結果

a:253

Solidityと同じ結果でした。256を足すと答えが出るみたいになってる。


u32をu16に変換する

let b:u32 = 0x12345678;
let c:u16 = b as u16;
println!("b:{}({:#x?}) -> c:{}({:#x?})", b ,b, c, c);
Enter fullscreen mode Exit fullscreen mode

結果

b:305419896(0x12345678) -> c:22136(0x5678)

Solidityと同じ結果でした。


u16をu32に変換する

 let d:u16 = 0x1234;
 let e:u32 = d as u32;
 let f:u32 = 0x00001234;
 println!("u16:{:#x?} u32:{:#x?} u32:{:#x?}", d, e, f);
Enter fullscreen mode Exit fullscreen mode

結果

u16:0x1234 u32:0x1234 u32:0x1234

Solidityと同じ結果ってことかなと思いました。器が大きくなっただけなので、値自体は全く変わっていない、と認識しました。


bytes2からbytes1にする

Solidityのドキュメントのこれです。
Solidityのドキュメント

int, uintの場合は、容量を減らすと大きい数値がなくなり小さい方が残りますが、byte列の場合は、大きい方が残ると認識しました。

Rustには、bytes2とかbytes1といった型は標準では多分なく、[u8; 2]みたいなu8型の配列やvectorで表すのかなと思います。下記は上記のSolidityの仕様と同じになるように、Rustでやってみたものです。

let g: u32 = 0x04030201;
let h: [u8; 4] = g.to_be_bytes();
let mut i: [u8; 2] = [0; 2];
i.clone_from_slice(&h[..2]);
let k: u16 = u16::from_be_bytes(i);
println!("{}({:#x?}) -> {:?} -> {}({:#x?})", g, g, h, k, k);
Enter fullscreen mode Exit fullscreen mode

結果

67305985(0x4030201) -> [4, 3, 2, 1] -> 1027(0x403)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay