Upgrade to Pro — share decks privately, control downloads, hide ads and more …

byte列のbit表現を得るencodingライブラリ作った

 byte列のbit表現を得るencodingライブラリ作った

66487f93d23ed4f64752cffbafdb938a?s=128

convto

May 19, 2022
Tweet

More Decks by convto

Other Decks in Programming

Transcript

  1. byteྻͷbitදݱΛಘΔ encodingϥΠϒϥϦ࡞ͬͨ golang.tokyo #32 2022-05-19 @convto

  2. @convto גࣜձࣾKyashॴଐ ϨΠϠ௿Ίͷٕज़΍҉߸ٕज़ʹڵຯ ͋Γ աڈʹ͸protobufͷ؆қతͳύʔα ʔॻ͍ͨΓplain RSA࣮૷ॻ͍ͨΓ ͠·ͨ͠

  3. ͸͡Ίʹ • ࣗ෼͕࢖͍͔ͨͬͨͷͰബ͍encodingϥΠϒϥϦΛ࡞ͬͨͷͰ঺հ͠·͢ • Ϟνϕʔγϣϯ • ࢖͍ํ • etc •

    ΍Γ͍ͨ͜ͱ͕ඪ४ϥΠϒϥϦͷencoding/hexʹΊͪΌΊͪΌࣅ͍ͯΔͷͰ͔ͳΓࢀߟʹ ͯ͠·͢ • Ҏલهࣄॻ͍ͨͷͰͦͬͪʹ΋·ͱ·ͬͯ·͢ • https://convto.hatenablog.com/entry/2022/05/08/160157
  4. github.com/ convto/bit ͨͱ͑͹೚ҙͷencodingͷόΠφϦදݱΛ֬ೝ͍ͨ͠ͱ͖ͳͲʹ࢖͑Δ https://go.dev/play/p/bs42fhnEbXh • όΠφϦΛ0ͱ1ͷจࣈྻͰ දݱ͢Δ • Encode/Decode/DumpΛ αϙʔτ

    • io.Reader/io.Writer΋࡞ΕΔ
  5. Contents 1. Ϟνϕʔγϣϯ 2. ར༻ํ๏ • Encode • Decode •

    Dump 3. ΍ͬͯΔ͜ͱ 4. ·ͱΊ
  6. Ϟνϕʔγϣϯ

  7. ੜͷbitදݱ஌Γ͍ͨͱ͖͋Δ • ৽͍͠encodingௐ΂ͯΔͱ͖ͱ͔͸όΠφϦͲ͏ͳͬͯΔͷ͔ؾʹͳΔ • byte੔ྻ͞Εͯͳ͍ͱ͖ʹhexͩͱ೴಺Ͱbitม׵ͯ͠ઌ಄Nbit͕ͳΜ΅Ͱɺޙଓͷbit͕ͳΜ΅Ͱ…ͱͳΓ໘౗ͳͷ ͰbitͰΈΕΔͱخ͍͠ • `xxd -b` ͱ͔ͰΈΕΔ͕GoϓϩάϥϜ͔Βॊೈʹ࢖͍͍ͨ

    • forϧʔϓͰ `fmt.Printf("%08b", src[i])` Έ͍ͨͳײ͡ʹ͢Δͷ΋͋Γ͚ͩͲҎԼͷ՝୊͕͋Δ • io͕ॊೈͰͳ͍ • ૉ๿ʹfmtύοέʔδʹґଘͯ͠ΔͷͰͦͦ͜͜ίετֻ͕͔Γͦ͏ • ग़ྗ͕ζϥʔͱͰ͖ͯͯಡΈͮΒ͍ɻdebug༻్ͳΒ͍͍ײ͡ʹग़ྗ͍ͨ͠ • ௐ΂ͨൣғͩͱͦ͏͍͏ظ଴ΛຬͨͤΔύοέʔδ͸ͳͦ͞͏ͩͬͨͷͰ࡞ͬͨ(bit୯Ґioͱ͔͸͋Δ)
  8. ར༻ํ๏

  9. σβΠϯ͸ encoding/hex Λࢀߟʹ͠·ͨ͠ • Encode/Decodeʹ͘Θ͑ioͷαϙʔτͱdumpग़ྗ • ͭ͡͸ encoding/hex ͸objdump૬౰ͷDumpΛαϙʔτͯ͠Δ •

    https://pkg.go.dev/encoding/hex#example-Dump • hex͸base64ͳͲͱҧͬͯ1char͋ͨΓ4bitදݱͰ8ͷ໿਺͔ͩΒbyte ੔ྻΛؾʹ͢Δඞཁͳ͍ͷ΋ࣅ͍ͯΔ
  10. Encode https://go.dev/play/p/XwAGDwtVj2t • hex΍base64ͱ͓ͳ͘͡ ඞཁͳsizeͷdst֬อ͸ݺ ͼग़͠ଆͷ੹຿

  11. Encode (io.Writer) https://go.dev/play/p/HdI5SrpCCUN • streamΛ͍͍ײ͡ʹѻ͍ ͍ͨͷͰio.Writer΋αϙ ʔτ

  12. Decode https://go.dev/play/p/7y7t1OqDpAn • decode΋͍͍ײ͡ͷdstΛ༻ҙ ͢Δͷ͸ݺͼग़͠ଆͷ੹຿ • bitදݱ͕8ͷഒ਺Ͱͳ͍ͱ͏· ͘byte͕࡞Εͳ͍ͷͰɺ8ͷഒ ਺Ͱͳ͍ͱ͖͸ΤϥʔΛ͔͑͠ ͯ·͢ɻhex΋ಉ༷ͷ࡞Γ

  13. Decode (io.Reader) https://go.dev/play/p/EoYkmkjn_e8 • ͬͪ͜΋io.ReaderΛαϙʔτ • bitදݱ͕8ͷഒ਺Ͱͳ͍ͱ͖ ͸ io.ErrUnexpectedEOF Λ

    ฦ͠·͢(ݻఆioͰΩϦ͕ѱ͍ ͱ͖ͷΤϥʔ)
  14. Dump https://go.dev/play/p/-_dKBj7TkOW • `xxd -b` ૬౰ͷग़ྗΛαϙʔτ • debug༻్ͳΒ͜Ε͕͓͢͢Ί • ݩόΠφϦΛ෮ݩ͍ͨ͠ͳΒ

    Encode/DecodeΛ࢖͏ɺΈͨ ͍ͳײ͡ͷ࢖͍෼͚Λ૝ఆ
  15. ΍ͬͯΔ͜ͱ

  16. ίΞ෦෼͸୯७ • ΍Γ͍ͨ͜ͱ͸byte͝ͱʹ8ݸͷbit දݱʹόϥ͚ͩ͢ • 1ඵͰࢥ͍͖ͭͦ͏ͳॲཧΛ͔ͭͬ ͍ͯ·͢ • ৭ʑ࣮૷Λൺֱ͍͕ͨ͠ɺ΍Γͨ ͍͜ͱࣗମ͕୯७ͳͷͰͦΜͳࠩ

    Ͱͳͦ͞͏Ͱ͜ͷ··ʹ͍ͯ͠Δ
  17. ·ͱΊ

  18. byteྻͷbitදݱಘΔύοέʔδͭͬͨ͘Α • encoding/hexΛࢀߟʹͨ͠Α • Encode/Decodeαϙʔτ, ioαϙʔτ, Dumpग़ྗαϙʔτ • όΠφϦͰ༡Ϳͱ͖ͷσόοά༻్Ͱͥͻʂ •

    ඪ४ͷencodingܥͷύοέʔδ͸ioͷѻ͍ͱ͔ͰษڧʹͳΔͷͰ͓ ͢͢Ί
  19. ͝ਗ਼ௌ͋Γ͕ͱ͏͍͟͝·ͨ͠ʂ