# Introduction

I don't particularly know where the fizz buzz trend came from. It might just be a meme or something, but it is somewhat popular.

# Challenge

Your job today is to convert Fizz Buzz into binary (0, 1) respectively, and convert that binary to text. Pretty standard stuff.

# How does that work?

FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz would translate into 01101000 01101001 then that would translate into "hi"

# Constraints

• Input is Fizz Buzz in a binary standpoint (see examples below.)
• Output must be text.
• You can assume the FizzBuzz input is right.
• This is , shortest bytes win.

# Input

FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz

# Output

"hi!"

• Meme? This is a primary (elementary) school game May 29, 2017 at 16:18
• Can we not take spaces in the input? May 29, 2017 at 16:18
• Can we not take that space though? I can save three bytes if I don't have to input that space. May 29, 2017 at 16:22
• FizzBuzz enjoys a lot of currency on Stack Exchange in part because Joel (one of the founders) had a blog post referencing another blog which talked about using it as a low barrier to entry problem for programming applicants. May 29, 2017 at 20:01
• @dmckee the "another blog" that Joel references is Jeff Atwood's, the other founder of Stackoverflow. May 30, 2017 at 5:22

## C, 59 bytes

i;f(char*s){while(*s&3?*s&9||(i+=i+*s%5):putchar(i),*s++);}

Magic numbers, magic numbers everywhere!

(Also, C shorter than Python, JS, PHP, and Ruby? Unheard of!)

This is a function that takes a string as input and outputs to STDOUT.

### Walkthrough

The basic structure is:

i;           // initialize an integer i to 0
f(char*s){
while(...);  // run the stuff inside until it becomes 0
}

Here, the "stuff inside" is a bunch of code followed by ,*s++, where the comma operater returns only the value of its second argument. Hence, this will run through the string and set *s to every character, including the trailing NUL byte (since postfix ++ returns the previous value), before exiting.

Let's take a look at the rest:

*s&3?*s&9||(i+=i+*s%5):putchar(i)

Peeling away the ternary and short circuiting ||, this can be expanded to

if (*s & 3) {
if (!(*s & 9)) {
i += i + *s % 5;
}
} else {
putchar(i);
}

Where do these magic numbers come from? Here are the binary representations of all the characters involved:

F  70  01000110
B  66  01000010
i  105 01101001
z  122 01111010
u  117 01110101
32  00100000
\0 0   00000000

First, we need to separate space and NUL from the rest of the characters. The way this algorithm works, it keeps an accumulator of the "current" number, and prints it whenever it reaches a space or the end of the string (i.e. '\0'). By noticing that ' ' and '\0' are the only characters to not have any of the two least significant bits set, we can bitwise AND the character with 0b11 to get zero if the character is space or NUL and nonzero otherwise.

Digging deeper, in the first "if" branch, we now have a character that's one of FBizu. I chose only to update the accumulator on Fs and Bs, so I needed some way to filter out the izus. Conveniently, F and B both have only the second, third, or seventh least significant bits set, and all the other numbers have at least one other bit set. In fact, they all have either the first or fourth least significant bit. Hence, we can bitwise AND with 0b00001001, which is 9, which will yield 0 for F and B and nonzero otherwise.

Once we've determined that we have an F or B, we can map them to 0 and 1 respectively by taking their modulus 5, because F is 70 and B is 66. Then the snippet

i += i + *s % 5;

is just a golfy way of saying

i = (i * 2) + (*s % 5);

which can also be expressed as

i = (i << 1) | (*s % 5);

which inserts the new bit at the least significant position and shifts everything else over 1.

"But wait!" you might protest. "After you print i, when does it ever get reset back to 0?" Well, putchar casts its argument to an unsigned char, which just so happens to be 8 bits in size. That means everything past the 8th least significant bit (i.e. the junk from previous iterations) is thrown away, and we don't need to worry about it.

Thanks to @ETHproductions for suggesting to replace 57 with 9, saving a byte!

• Nice trick with the putchar. May 29, 2017 at 18:18
• This is reeeeeally awesome. C did right! May 30, 2017 at 0:41
• Speaking of doing things right, this is, in my not-so-humble opinion, how a code-golf answer should be done. You post a clever, insightful solution, accompanied by a complete, well-written explanation that actually teaches people something about the language that might be useful in other, more practical circumstances. May 30, 2017 at 7:50
• @CodyGray Exactly this. One of the reasons that Code Golf isn't on the top of my SE that I visit frequently is because a lot of answers are just "here's the code". While that's cool for people who are very familiar with the languages, it just looks like noise to me. I like to see the explanations like here because it reveals the method, which I would think most people find a lot more interesting than the code itself. Just my two cents... May 30, 2017 at 13:10
• Very nice bithack, but you count your bits from MSB(left) to LSB(right)? IMO the only sane way to count bits in an 8-bit byte (or a 128-bit SIMD vector, or whatever) is from LSB=bit 0 to MSB=bit 7. May 30, 2017 at 21:14

# Jelly, 9 bytes

Ḳm€4O%5ḄỌ

Try it online!

• Oh smart, flattening it was unnecessary. Nice. May 29, 2017 at 16:33
• @HyperNeutrino Note the comment I've made on yours, I've used a slightly different algorithm so as to avoid duping (even though technically allowed I don't like it). May 29, 2017 at 16:33
• @downvoter: did you test this at all before drive-by downvoting? May 30, 2017 at 9:04

# Bash + coreutils, 61 50 bytes

(-11 bytes thanks to Doorknob!)

tr -d izu<<<$1|tr FB 01|dc -e'2i?[aPz0<k]dskx'|rev Try it online! • You can replace the sed with tr FB 01|tr -d izu to save 11 bytes. May 29, 2017 at 18:38 # Python 3, 169101939185 81 bytes lambda s,j="".join:j(chr(int(j('01'[b<"C"])for b in c[::4]),2))for c in s.split()) Try it online! Explanation: lambda s,j="".join: # Create a lambda function j( # call "".join, adds characters together with nothing in between chr( # character by int int( # string to int j( # "".join again '01'[b<"C"] # 1 or 0, based on what character we get for b in c[::4] # For every first of 4 characters ), 2) # Base 2 ) for c in s.split() # for every group of Fizz and Buzz with any whitespace character after it ) • That was fast. +1 May 29, 2017 at 16:18 • I did something similar to this a while ago, it was just a matter of copy-paste and change it to FizzBuzz :P May 29, 2017 at 16:23 • Oh that explains. :P But you got outgolfed ;_; May 29, 2017 at 16:25 • Outgolfed again - Try it online! (89 bytes) May 29, 2017 at 17:55 • Whoops, did it again, 85 bytes this time with a lambda function May 29, 2017 at 17:59 ## JavaScript (ES6), 80 79 bytes let f = s=>${s} .replace(/.{4} ?/g,m=>m[s=s*2|m<'F',4]?String.fromCharCode(s&255):'')

console.log(f("FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz"))

• Very nice. I tried and failed to come up with something shorter, though there are several alternate 80-byte solutions using .replace(/..zz/g,, '0b'+, etc. May 29, 2017 at 20:20
• @ETHproductions Getting rid of n allows to reach 79. Sadly, this requires an extra space to be added to the input. Hence the rather costly ${s}  . May 30, 2017 at 11:01 # Japt, 262419 17 bytes ¸®ë4 ®c u5Ãn2 dÃq Try it online! Saved 2 bytes thanks to @Shaggy & 2 bytes thanks to @ETHproductions ### Explanation input: "FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz" ¸® // ["FizzBuzzBuzzFizzBuzzFizzFizzFizz","FizzBuzzBuzzFizzBuzzFizzFizzBuzz","FizzFizzBuzzFizzFizzFizzFizzBuzz"] ë4 // ["FBBFBFFF","FBBFBFFB","FFBFFFFB"] ®c // [[70,66,66,70,66,70,70,70],[70,66,66,70,66,70,70,66],[70,70,66,70,70,70,70,66]] u5Ã // ["01101000","01101001","00100001"] n2 // [104,105,33] d // ["h","i","!"] Ãq // "hi!" • You can replace the 2 }) with Ã. There's definitely more to be saved than that but I can't quite get it working on my phone. May 29, 2017 at 19:08 • Very nice, thanks for using Japt! You can save a couple bytes by replacing ò4...q n2 with ë4...n2 (ë4 does the same thing as ò4, except returning only the first item; strangely, it doesn't seem to be documented) May 29, 2017 at 20:10 • @ETHproductions Thanks for making Japt! May 29, 2017 at 20:17 • Finally got around to that shorter version - only took 3 years! codegolf.stackexchange.com/a/211146/58974 Sep 16, 2020 at 16:39 ## Ruby, 6563 60 bytes ->s{s.split.map{|x|x.gsub(/..../){$&.ord%5}.to_i(2).chr}*''}

This is an anonymous proc that takes input and gives output as a string.

->s{
s.split            # split on whitespace
.map{|x|           # for each word as x,
x.gsub(/..../){  # replace each sequence of four characters with
$&.ord%5 # the ASCII value of the first character, mod 5 # F is 70, B is 66, so this yields 0 for Fizz and 1 for Buzz }.to_i(2) # interpret as a binary number .chr # the character with this ASCII value }*'' # join on empty string } # JavaScript (ES6), 958885 81 bytes s=>s.replace(/..zz/g,m=>m<"F"|0).replace(/\d+ ?/g,m=>String.fromCharCode("0b"+m)) ## Try it f= s=>s.replace(/..zz/g,m=>m<"F"|0).replace(/\d+ ?/g,m=>String.fromCharCode("0b"+m)) oninput=_=>o.innerText=f(i.value) o.innerText=f(i.value="FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz") *{font-family:sans-serif} <input id=i><p id=o> • I believe + is shorter than parseInt May 29, 2017 at 16:49 • I think +(m[0]<"F") could be shortened to m<"F"|0 May 29, 2017 at 17:45 # Perl 5, 33 Bytes print(pack'B*',<>=~y/FB -z/01/dr) Replaces 'F' and 'B' in the input with 0 and 1 respectively, and deletes the other characters. It then uses perl's pack function to turn this bit string into ASCII characters. • Wow this is golfed down to about half the size of my Perl 5 attempt. Kudos. May 29, 2017 at 23:07 • I believe you could make this considerably shorter using the -p0 command line option (which would save you <>=~r for input, and allow you to use$_= rather than print()). Depending on how you want to handle newlines, you might not even need the 0. (Even if you want to avoid command line option penalties, say is shorter than print.)
– user62131
May 29, 2017 at 23:15
• @Chris Not mine, faubiguy's. But thanks. ;) May 29, 2017 at 23:49
• You definitely don't need the 0 either. Just use the -p flag and $_=pack'B*',y/FB -z/01/dr for your program lowers your score to 26 bytes. May 29, 2017 at 23:52 # Python 2, 908382 81 bytes -1 byte thanks to totallyhuman -1 byte thanks to Martmists -1 byte thanks to Jonathan Frech lambda x:''.join(chr(int([+(l<'D')for l in b[::4]][1::3],2))for b in x.split()) Try it online! • Sans a byte. May 29, 2017 at 16:37 • you can save a byte by turning *1 for into *1for May 29, 2017 at 16:42 • Since you use *1 to convert from boolean to integer, you can save a byte by using a +: (l<'D')*1for can be +(l<'D')for. Nov 12, 2017 at 13:36 # Whitespace, 123 bytes Visible representation: SSNNSSNSNSSSNSNSTNTSTTTSSSTSSSSSNTSSTSNSNTSSNSSSTSSTTSNTSSTNTSTNSSSTNTSSSNSSTNSSNSNSSNSTNTSTNTSTNTSTSSSNSNNNSSSNSNTTNSSNSNN Unobfuscated program: push 0 loop: dup push 0 dup ichr get push 32 sub dup jz space push 38 sub jz fizz push 1 add fizz: push 0 dup dup ichr ichr ichr add jmp loop space: swap pchr jmp loop There's nothing particularly odd about the implementation, the only real golfing is in some strange reuse of temporaries as well as not caring about the unbounded stack growth to skim down some more bytes. # Octave, 5957 53 bytes @(s)['',bi2de(flip(reshape(s(65<s&s<71)<70,8,[]))')'] This doesn't work on TIO, since the communication toolbox is not implemented. It works fine if you copy-paste it to Octave-online. It's not even close to be working code in MATLAB. Managed to save two bytes by transposing the matrix after flipping it, instead of the other way around. ### Explanation: @(s) % Anonymous function that takes a string as input ['',<code>] % Implicitly convert the result of <code> to its ASCII-characters Let's start in the middle of <code>: s(65<s&s<71) % Takes the elements of the input string that are between 66 and 70 (B and F) % This gives a string FBBFFBBFBBBFFFBF... s(65<s&s<71)<70 % Converts the resulting string into true and false, where F becomes false. % Transformation: FBBFFB -> [0, 1, 1, 0, 0, 1] Let's call the resulting boolean (binary) vector for t. reshape(t,8,[]) % Convert the list of 1 and 0 into a matrix with 8 rows, one for each bit flip(reshape(t,8,[])) % Flip the matrix vertically, since bi2de reads the bits from the wrong end flip(reshape(t,8,[]))' % Transpose it, so that we have 8 columns, and one row per character bi2de(.....)' % Convert the result decimal values and transpose it so that it's horizontal # Perl 5, 28 bytes+4 bytes for flags=32 bytes Run with the flags -040pE$_=chr oct"0b".y/FB -z/01/dr

-040 sets the record separator to a space so that perl sees each group of FizzBuzzes as a separate line, then loops over those lines, changing F to 0, B to 1, deleting everything else, then converting to binary and from there to ascii.

# Jelly, 9 bytes

Ḳm€4=”BḄỌ

Try it online!

Ḳ          Split on spaces
€        Map
m 4       Take every fourth letter (F and B)
=”B    Check if each letter is equal to B (gives the binary representation)
Ḅ   Binary -> Integer
Ọ  Unord; gives chr(i)

-3 bytes thanks to Erik the Outgolfer

• May 29, 2017 at 16:37

# PHP, 67 Bytes

Limited to 8 letters

Try it online!

# Brain-Flak, 107 bytes

{(((((()()()()){}){}){})({}[{}])()())((){[()](<{}>)}{}<>)<>{(<{}{}{}{}>)<>({}({}){})<>}{}}<>{({}<>)<>}<>

Try it online!

+3 bytes for the -c flag.

### Explanation

{                                        For each character in input:
(((((()()()()){}){}){})({}[{}])()())    Push 32-n and 66-n
((){[()](<{}>)}{}<>)<>                  If character is B, push 1 on second stack.  Otherwise, push 0
{                                       If character is not space:
<>({}({}){})<>                         Multiply current byte by 2 and add previously pushed bit
}                                       (otherwise, the pushed 0 becomes the new current byte)
{}                                      Remove character from input
}
<>{({}<>)<>}<>                           Reverse stack for output

# q/kdb+, 414037 33 bytes

Solution:

{10h$0b sv'66=vs[" ";x][;4*(!)8]} Example: q){10h$0b sv'66=vs[" ";x][;4*(!)8]}"FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz"
"hi!"

Explanation:

Split the input string on " " to give distinct lists of FizzBuzz..., index into each of these lists at the first character (ie 0 4 8 ... 28). Return boolean list determined by whether each character is "B" (ASCII 66). Convert these lists to base 10, and then cast result to string.

{10h$0b sv'66=vs[" ";x][;4*til 8]} / ungolfed solution { } / lambda function with x as implicit input vs[" ";x] / split (vs) input (x) on space (" ") til 8 / til 8, the range 0..7 inclusive 4* / vectorised multiplication, 0 1 2 3 => 0 4 8 12 [; ] / index the 2nd level at these indices (0, 4, 8 ... 28) 66= / 66 is ASCII B, 66="FBBFBFFF" -> 01101000b 0b sv' / join (sv) each row back with 0b (converts from binary) 10h$                              / cast to ASCII (0x686921 -> "hi!")

Try it online!

How it works

words      -- split input string into words at spaces
(>>=      )            -- map the function to each word and flatten the resulting
-- list of strings into a single string
\w->                -- for each word w
[  |c<-w,c<'a'] -- take chars c that are less than 'a' (i.e. B and F)
mod(fromEnum c)5  -- take ascii value of c modulus 5, i.e. convert to bit value
foldl1((+).(2*))   -- convert list of bit to int
toEnum(   ):""       -- convert ascii to char.  :"" forces toEnum to be of type String
-- now we have a list of single char strings, e.g. ["h","i","!"]

# JavaScript ES6 - 98 bytes

too many bytes, but at least readable

Defined as function it is 98 bytes

let s=>s.replace(/(F)|(B)|./g,(c,F,B)=>B?1:F?0:'').replace(/.{8}/g,v=>String.fromCharCode('0b'+v))

test:

"FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz"
.replace(/(F)|(B)|./g,(c,F,B)=>F?0:B?1:'').replace(/.{8}/g,v=>String.fromCharCode('0b'+v))

### Explanation:

/(F)|(B)|./

Matches the F and B letters and anything else as Groups

(c,F,B)=>F?0:B?1:''

is a Function that captures the groups , returns a 0 for F and 1 for B , or ''

c is the character matched
F and B are now Parameters!
the 3rd . group is ommitted as parameter

F and B are undefined when the 3rd group is matched
B is undefined when group F is matched

The resulting 0100.. etc string

is cut in slices of 8 bytes

.replace(/.{8}/g,v=>String.fromCharCode('0b'+v))

and processed as 0b binary string

• Welcome to PPCG! The objective of this challenge is to provide a program or function translating arbitrary FizzBuzz strings. I don' know much JavaScript, but a valid function submission might be s=>s.replace( .... Also please do include a byte count in the Header of your answer. May 29, 2017 at 19:12
• I cleaned up some of your code formatting for you. Also, you don't need the let, anonymous functions are acceptable. May 30, 2017 at 11:56

# shortC, 35 bytes

i;AW*@&3?*@&9||(i+=i+*s%5):Pi),*s++

Conversions in this program:

• A - int main(int argc, char **argv){
• W - while(
• @ - argv
• P - putchar(
• Auto-inserted );}

Heavily based off of Doorknob's answer.

# APL (Dyalog Classic), 17 bytes

{82⎕DR'B'=⍵∩'BF'}

## Explanation

⍵∩'BF'    cut, removes all but 'BF' from ⍵
'B'=          equals 'B' turns it into binary stream
82⎕DR              converts into character stream

Try it online!

# Japt-P, 9 bytes

Or 8 bytes if input can be lowercase.

¸Ën"FB" d

Try it

¸Ën"FB" d     :Implicit input of string
¸             :Split on spaces
Ë            :Map
n"FB"       :  Convert from base "FB" to decimal, ignoring all other characters
d     :  Get the character at that codepoint
:Implicitly join and output

# 05AB1E, 15 bytes

#vy„FBÃS'BQ2βçJ

Try it online!

=ArrayFormula(JOIN("",CHAR(BIN2DEC(SPLIT(SUBSTITUTE(SUBSTITUTE(A1,"Fizz",0),"Buzz",1)," ")))))

I'm not familiar with FizzBuzz binary but it seems that they're delineated by spaces so this formula relies on that. The logic is pretty simple:

• Replace Fizz with 0 and Buzz with 1
• Split the result into an array using a space as a delimiter
• Convert each element from binary to decimal
• Replace each element with its ASCII equivalent
• Join each element without a delimiter

# Java 8, 117 115 bytes

s->{for(String x:s.split(" "))System.out.print((char)Long.parseLong(x.replace("Fizz","0").replace("Buzz","1"),2));}

I doubt you can do a lot of the fancy regex replacements in Java like most other answers, mainly because you can't do anything with the captured capture-groups in Java-regexes.. (I.e. "$1".charAt(...) or "$1".replace(...) aren't possible for example.)

Explanation:

Try it here.

s->{                          // Method with String parameter and no return-type
for(String x:s.split(" "))  //  Loop over the input split by spaces:
System.out.print(         //   Print:
(char)                   //    Each character
Long.parseLong(          //    after we've converted each binary-String to a long
x.replace("Fizz","0").replace("Buzz","1")
//    after we've replaced the Fizz/Buzz to 0/1
,2));
}                             // End of method

# J, 20 bytes

a.{~_8#.\2-.~'FB'i.]

Try it online!