2
$\begingroup$

I'm trying to pad some binary and hexadecimal numbers using PaddedForm, and also to separate the digits into blocks of 4. For example, I'd like a number like 17651 to be printed in binary as 0000 0000 0000 0000 0100 0100 1111 0011, perhaps.

I tried the following (output included):

PaddedForm[BaseForm[17651, 2], 32, DigitBlock -> 4, 
 NumberSeparator -> " ", NumberPadding -> "0"]

0000000000000000000000100 0100 1111 0011

I also tried the following:

PaddedForm[BaseForm[17651, 2], 32, DigitBlock -> 4, 
 NumberSeparator -> " ", NumberPadding -> "0000 "]

0000 0000 0000 0000 00100 0100 1111 0011

Neither one properly handles both the padding on the left side and the DigitBlock separator.

I can make a complicated function like the below, but is there a way to get PaddedForm to play nice with the DigitBlock option?

PaddedBlockForm[int_, base_ : 10, minDigits_ : 1, block_ : 9999] := 
 Module[{extraDigits, preRiffle, digits},
  
  preRiffle = IntegerString[int, base];
  digits = Max[minDigits, StringLength@preRiffle];
  extraDigits = Mod[block - Mod[digits, block], block];
  
  ToUpperCase@StringDrop[
    StringRiffle@
     StringPartition[
      StringPadLeft[
       preRiffle,
       digits + extraDigits,
       "0"
       ],
      block
      ],
    extraDigits
    ]
  ]
$\endgroup$
1
  • 1
    $\begingroup$ Sorry but I'm not sure what the problem is with your second output. Does StringInsert[IntegerString[17651, 2, 32], " ", 1 + 4*Range[8]] produce the desired output? $\endgroup$
    – anderstood
    Dec 28, 2021 at 19:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.