Skip to Main Content
Ruby. Receptury
book

Ruby. Receptury

by Lucas Carlson, Leonard Richardson
November 2012
Intermediate to advanced content levelIntermediate to advanced
888 pages
54h 46m
Polish
Helion
Content preview from Ruby. Receptury

2.6. Konwersje między różnymi podstawami liczenia

Problem

Chcemy wyrażać wartości liczbowe w różnych układach liczenia.

Rozwiązanie

Stałe binarne, ósemkowe i szesnastkowe zapisuje się, rozpoczynając od prefiksu (odpowiednio) 0b, 0o i 0x:

0b100                          # => 4
0o100                          # => 64
0x100                          # => 256

Możliwa jest także konwersja wartości liczbowej do równoważnego jej łańcucha, wyrażonego w systemie liczenia o dowolnej podstawie z zakresu od 2 do 36 — należy podstawę tę podać jako argument wywołania metody Integer#to_s.

42.to_s(10)                       # => "42"
-100.to_s(2)                      # => "-1100100"
255.to_s(16)                      # => "ff"
1442151747.to_s(36)               # => "number"

Konwersję odwrotną wykonuje się za pomocą metody String#to_i wywoływanej z podstawą liczenia jako argumentem:

"1045".to_i(10) # => ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

ReasonML Quick Start Guide

ReasonML Quick Start Guide

Raphael Rafatpanah, Bruno Joseph D'mello
Microsoft Excel: Formeln & Funktionen - Das Maxibuch, 3., aktualisierte und erweiterte Auflage

Microsoft Excel: Formeln & Funktionen - Das Maxibuch, 3., aktualisierte und erweiterte Auflage

Egbert Jeschke, Eckehard Pfeifer, Helmut Reinke, Sara Unverhau, Bodo Fienitz
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao

Publisher Resources

ISBN: 9781457177453Errata Page