fork download
  1. #!/usr/bin/perl
  2.  
  3. # Idiom #310 Fill array with random bytes
  4.  
  5. my $n = 20;
  6.  
  7. my $bytestring;
  8. foreach my $i (0 .. $n*8 - 1) {
  9. vec($bytestring, $i, 1) = rand(2);
  10. }
  11.  
  12. my $i = 0;
  13. foreach my $c ( split //, $bytestring ) {
  14. my $bytes_in_binary = unpack 'B*', $c;
  15. printf "%4d %s\n", ++$i, $bytes_in_binary;
  16. }
  17.  
  18. printf "Length of bytestring in bytes: %d\n", length $bytestring;
  19. vec($bytestring, $n*8, 1) = 1;
  20. printf "Length after extending by one bit: %d\n", length $bytestring;
  21. printf "Binary value of last byte: %s\n", unpack 'b*', substr $bytestring, -1, 1;
  22.  
  23.  
Success #stdin #stdout 0.01s 5408KB
stdin
Standard input is empty
stdout
   1  01011010
   2  00100010
   3  00100011
   4  10011000
   5  01100001
   6  11110000
   7  11010110
   8  11111101
   9  01011111
  10  01101011
  11  11111110
  12  01111011
  13  00100010
  14  11101000
  15  01000010
  16  10011101
  17  11101100
  18  01110011
  19  00110001
  20  00000010
Length of bytestring in bytes: 20
Length after extending by one bit: 21
Binary value of last byte: 10000000