liveBook · Manning

Bytes

As explained in The Well-Grounded Rubyist, Fourth Edition

A byte is a unit of digital data consisting of eight bits and serving as a basic unit of file storage and input.

A byte is a unit of digital data represented by an integer. Strings consist of sequences of bytes, but the mapping from bytes to characters depends on encoding; one character may occupy one or more bytes. section 10.11.3 section 8.1.6

Bytes become visible when Ruby processes strings and input streams at a low level:

  • Use each_byte to enumerate a string's byte values rather than its characters. section 10.11.3
  • Use getbyte to move through a file or IO stream byte by byte; getc instead returns characters. section 12.2.3
  • Remember that byte counts and character counts can differ when the encoding uses multiple bytes per character. section 12.2.3
  • Treat IO#write's return value as the number of bytes written. section 12.1.1

XOR-ing string bytes

The string "a" contains one byte with value 97. XOR-ing it with 35, the value associated with "#", produces 66: 97 ^ 35. Applying the same XOR again restores 97, because (a ^ b) ^ b == a. Repeating a key across a string therefore provides a reversible byte-wise transformation. section 10.11.3

Listing 10.6 An exclusive-or method for strings
class String
  def ^(key)             1
    kenum = key.each_byte.cycle      2
    each_byte.map {|byte| byte ^ kenum.next }.pack("C*") 3
  end
end

This compact method cycles through a key's bytes, XORs them with the receiver's bytes, and packs the resulting integers back into a string. section 10.11.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains integer representation, encoding differences, stream operations, and a worked XOR transformation without covering binary storage internals.
Examples
Uses ASCII-valued characters, repeated-key XOR, each_byte, getbyte, getc, and IO#write examples.
What it assumes
Assumes familiarity with strings and basic numeric or bitwise operations while explaining encoding differences directly.
What you can do after
Apply byte-wise enumeration, file reading, and reversible XOR transformations in Ruby.
How it connects
Connects bytes with strings, characters, encoding, bitwise XOR, files, and IO streams.

Also explained in

Compare how 7 books explain bytes →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.