diff --git a/gcc/testsuite/gfortran.dg/pr117820.f90 b/gcc/testsuite/gfortran.dg/pr117820.f90
new file mode 100644
index 0000000000000000000000000000000000000000..59a4b363e05678357c6c9a2bf35b4c778347086b
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr117820.f90
@@ -0,0 +1,10 @@
+! { dg-do run }
+! See pr117820, original testcase provided by Malcolm Cohen.
+program test
+  integer(8) :: x
+  character(80) :: output
+  output = "garbage"
+  x = ibset (0_8, 63)
+  write(output, '("<",B64.0,">")') x
+  if (output .ne. "<1000000000000000000000000000000000000000000000000000000000000000>") stop 1
+end program
diff --git a/libgfortran/io/write.c b/libgfortran/io/write.c
index 2f414c6b57d26c2595b9228033959cdddfb8a616..ccb2b5cb810a0ce53f933cd9077f92db4241e84d 100644
--- a/libgfortran/io/write.c
+++ b/libgfortran/io/write.c
@@ -1392,6 +1392,10 @@ write_b (st_parameter_dt *dtp, const fnode *f, const char *source, int len)
     {
       n = extract_uint (source, len);
       p = btoa (n, itoa_buf, sizeof (itoa_buf));
+
+      /* Test for zero. Needed by write_boz.  */
+      if (n != 0)
+	n = 1;
       write_boz (dtp, f, p, n, len);
     }
 }