[Question]
  [
Given a binary message, and the number of parity bits, generate the associated parity bits.
A parity bit is a simple form of error detection. It's generated by counting the number of `1`'s in the message, if it's even attach a `0` to the end, if it's odd attach `1`.  
That way, if there's a 1-bit error, 3-bit error, 5-bit error, ... in the message, because of the parity-bit you know the message has been altered.  
Although if there were an even number of bits altered, the parity stays the same, so you wouldn't know if the message has been changed.  
Only *50%* of the time you'd know if bits have been altered with one parity bit.
## Generate Parity bits
To generate `n` parity bits for a given binary message:
1. Count the number of `1`'s in the message
2. Modulo by \$2^n\$
3. Attach the remainder to the message
For example, using three parity bits (n=3) and the message `10110111110110111`:
1. `10110111110110111` -> 13 `1`'s
2. \$13\mod2^3\$ -> 5
3. `10110111110110111` with 5 attached (in binary) -> `10110111110110111101`
The last three digits act as parity bits.  
The advantage with parity bits is, that they can't detect errors only when a multiple of \$2^n\$ bits have been altered (ignoring messages which share the same permutations). With three parity bits, you can't detect errors when 8, 16, 24, 32, 40, ... bits have been altered.  
\$(1-\frac{1}{2^n})\%\$ of the time you'd know when bits have been altered, significantly more than with just one parity bit.
## Rules
* Take as input a binary string or a binary array and an integer (`0<n`, the number of parity bits)
* Output a binary string/binary array with `n` parity bits attached
* The parity bits should be padded with zeros to length `n`
* Leading zeros are allowed
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins
## Test Cases
```
[In]:  10110, 1
[Out]: 101101
[In]:  0110101, 2
[Out]: 011010100
[In]:  1011101110, 3
[Out]: 1011101110111
[In]:  0011001100111101111010011111, 4
[Out]: 00110011001111011110100111110010
```
  
[Answer]
# [Zsh](https://www.zsh.org/) `--extendedglob`, 37 bytes
```
local -Z$2 -i2 n=${1//10#/+1}
<<<$1$n
```
[Try it online!](https://tio.run/##bU/LasMwELzrK5ZIBYlg7FVzCm4@pKUHJd46BlkKslryIN/uSrFbfIjEIoaZnRldh@M4UPSnCHSO5BpqWuv37GRCFy9SyURCcWZbWElxw7LEipdrvKsXrGuhV6P1B2OheBcaik6De1uqWJ1EKNyo2OwIWCFWgH8wo3RBL/lp4PVflFXzTGReerwIG8YYh/77cATrXUthy4yNmKozSGdqcJM2td3V1U4JKT8415/PvqPUnalsF6j3PzSAJdN0roUrBZ/gV/A97C@RhhjI9DlIL4Nma83Fw279PCNFjL8 "Zsh – Try It Online")
The `-Z$2` flag does the heavy lifting. It automatically `% base**$2`, and fills in zeroes. EXTENDED\_GLOB `10#` is equivalent to regex `10*`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~37~~ 36 bytes
```
->n,d{n+"%0*b"%[d,n.count(?1)%2**d]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ6U6T1tJ1UArSUk1OkUnTy85vzSvRMPeUFPVSEsrJbb2f4FCWrSSgYGhIQwDSQgB4Rgq6SiYxP4HAA "Ruby – Try It Online")
Thanks @dingledooper for -1 byte.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~79~~ \$\cdots\$ ~~74~~ 62 bytes
```
p;f(*b,n){for(p=0;*b|n;)printf("%d",*b?*b++&1&&++p:p>>--n&1);}
```
[Try it online!](https://tio.run/##fVHLboMwELznK1ZIQTyMCkl7aNykhyq3/EHJAYxJUNMNwpaKmvLrpTY2CVLVGq283hnPrBcWsVOGh76vaekFOUH/Up4br17HNMi/kPp1U6EsPWdeOCTIn4M8DN3EdcOwXtWbTRShm/i06xUJ3rMKPR8uM1BLFQKQXEjxuoc1XHZOEidJ7BDYOTpR35DrqgkDacyGqWvqsCdOR0fpQRmNckJgQWBJ4N7i7Jg1AfC25kzywpCMu7Yc3WNtOLHXBhr9pwG1xWMT7IxCWit25OyNN9YpbbeLtH18UfGgFSfn5XhbzRg8/Y4KC96qazG16ROI6pOfS2/s37@zheBaoRCGA9sfxMzAb0NXcmbwA2dPpzCgRfEXev3TJ0FgXqQY2bUB9QxJAP0bufQkmZ7tzJX4de5/6ae4tZQVzEWKSpxbpW7W9d@sPGUH0UcfPw "C (clang) – Try It Online")
*Saved ~~a~~ ~~4~~ a whopping 16 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!*  
*Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs a wide char string and an integer.  
Outputs the result to `stdout`.
[Answer]
# Excel (ms365), ~~50~~ 47 bytes
-3 Thanks to @[EngineerToast](https://codegolf.stackexchange.com/questions/252491/generate-parity-bits/252548#comment562308_252548)
```
=A1&BASE(MOD(LEN(SUBSTITUTE(A1,0,)),2^B1),2,B1)
```
[![enter image description here](https://i.stack.imgur.com/9p28e.png)](https://i.stack.imgur.com/9p28e.png)
[Answer]
# [Haskell](https://www.haskell.org/), ~~60~~ 42 bytes
```
b!n=b++[mod(sum b`div`2^(n-x))2|x<-[1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0kxzzZJWzs6Nz9Fo7g0VyEpISWzLMEoTiNPt0JT06imwkY32lBPLy829n9uYmaegq1CSr4Cl0JBUWZeiYKKQrShjoGOIRAaxCooKhjCJBDCOoaxMEElJSR9cGmwEqBeI7heFCkgNsBuAswKJBpkjjGGGzBoXC6CWYxKIxsAdxKcD3a7CZLbyTIEygP5lEvhPwA "Haskell – Try It Online")
* saved 3 Bytes thanks to @Unrelated String suggesting using list comprehension.
* saved 10 Bytes by @xnor by removing a redundant modulo.
Please check [his answer](https://codegolf.stackexchange.com/a/252534/84844) which is still one byte shorter using a more direct approach.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~11~~ 10 bytes
```
⌊∑$E%Π⁰↳›J
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIriiJEkRSXOoOKBsOKGs+KAukoiLCIiLCIwMTEwMTAxXG4yIl0=)
"~~11~~ 10 bytes?!" I hear you say. Well you gotta remember that when it comes to doing things with base conversion I don't do the best - so keep that in mind when y'all start giving me golfing suggestions :p
## Explained
```
⌊∑$E%Π⁰↳›J
⌊∑         # Sum of the 1s in the input binary
  $E%      # Modulo'd by 2 to the power of n
     Π     # Converted to binary
      ⁰↳   # Padded with spaces to make sure it's of length n
        ›J # With those spaces replaced with 0s and joined to the original binary input
```
[Answer]
# [Factor](https://factorcode.org/), 62 bytes
```
[ dup bin> bit-count pick 2^ mod >bin rot 48 pad-head append ]
```
[Try it online!](https://tio.run/##fZCxbgMhDIZ3nuLP7VdBmiFqpaxVly5RpyqRCLg6lB4Q4NQhyrNfCKBMTS0ZG@zPP/K3VMmF@XP7/vH2AhmjUxFHCpZ@MMo0PHkZIoWS14eDSb8mEiKdJrKKIozDK2NnhmxnCHSCC8E7XPDAFigdohFLdOXKxUNmgdbBeYOeq0z1v7kqc/cGrrLabVjzWiuTb7F8Iav905EDZxc2f0FPHgdjN/lIvXKTTfBGHbHcY3Qam1xDcAmrNbzU/UBSQ3pPVmOXcR9MJnZQbvQub7RsvyephvkK "Factor – Try It Online")
Takes input as `n msg`.
```
          ! 3 "10110111110110111"
dup       ! 3 "10110111110110111" "10110111110110111"
bin>      ! 3 "10110111110110111" 94135
bit-count ! 3 "10110111110110111" 13
pick      ! 3 "10110111110110111" 13 3
2^        ! 3 "10110111110110111" 13 8
mod       ! 3 "10110111110110111" 5
>bin      ! 3 "10110111110110111" "101"
rot       ! "10110111110110111" "101" 3
48        ! "10110111110110111" "101" 3 48
pad-head  ! "10110111110110111" "101"
append    ! "10110111110110111101"
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~8.5~~ 7.5 bytes (15 nibbles)
```
:$\<@\``@+^2@+
```
Input and output both as arrays of `0`s and `1`s.
```
             +       # get the sum of arg1,
         +           # and add it to
          ^2         # two to the power of
            @        # arg2,   
      ``@            # convert to binary digits,
     \               # reverse them,
   <@                # take arg2 elements,
  \                  # and reverse them back again
                     # (so the last few steps effectively
                     # pad the binary digits to arg2 digits),
:$                   # finally, append this onto arg1
```
[![enter image description here](https://i.stack.imgur.com/cnsgy.png)](https://i.stack.imgur.com/cnsgy.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
tsiW\2M&Bh
```
[Try it online!](https://tio.run/##y00syfn/v6Q4MzzGyFfNKeP//2hDBQMFQwUYaYjEhorEchkDAA) Or [verify all test cases](https://tio.run/##y00syfmf8L@kODM8xshXzSnjv0vI/2hDBQMFQyA0iOUy5IqGsiE4lsuICy6PRMdyGYNUwtSi0sgqYSYh@EAzTQA).
### Explanation
```
t    % Implicit input: numeric vector. Duplicate
s    % Sum
i    % Input: number, n
W    % 2 raised to that
\    % Modulo
2M   % Push n again
&B   % Binary expansion with specified number of digits
h    % Concatenate horizontally. Implicit display
```
[Answer]
# JavaScript (ES6), 53 bytes
Expects `(binary_string)(n)` and returns another binary string.
```
s=>g=(n,k)=>k^n?g(n,-~k)+(~-s.split`1`.length>>k&1):s
```
[Try it online!](https://tio.run/##bYxBCsIwEEX3HqMLyaAJHXUlJN6ktNQ01oSkdILLXj1NrCuV4TMDb95/dq@O@nmcIvfhrtMgE0llJPNHC1LZxt9Mvvli4cAWToImN8YWW@G0N/GhlN0jXCn1wVNwWrhg2MAqrBHrChgC7L5QIXkyPP3C4m3J/PxHLvYn22Mpe@/SeAFIKw "JavaScript (Node.js) – Try It Online")
### Commented
It's a little easier to build the output from right to left. This way, we can just append the input string on the last recursive call.
```
s =>             // outer function taking the binary string s
g = (n,          // inner recursive function taking n
        k) =>    // and a counter k which is initially undefined
k ^ n ?          // if k is not equal to n:
  g(n, -~k) +    //   do a recursive call with k + 1
  (              //   append one binary digit:
    ~-s.split`1` //     to get the number of 1's, subtract 1 from the length
    .length      //     of the array obtained by splitting the input on 1's
    >> k & 1     //     right shift by k positions and keep the LSB
  )              //
:                // else:
  s              //   append s and stop the recursion
```
[Answer]
# [Python](https://www.python.org), 48 bytes
```
lambda a,b:b+bin(b.count("1")%2**a)[2:].zfill(a)
```
Finally, a use for `zfill`!
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jdJscxJzk1ISFRJ1kqyStJMy8zSS9JLzS_NKNJQMlTRVjbS0EjWjjaxi9arSMnNyNBI1ITq3FhRlAtWkaRjpKBkYGhoAoZImVA5mOgA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
SBŻ⁹¡ṫC}⁸;
```
A dyadic Link that accepts a list of bits on the left and a positive integer on the right and yields a list of bits extended with the parity bits.
**[Try it online!](https://tio.run/##y0rNyan8/z/Y6ejuR407Dy18uHO1c@2jxh3W////jzbUgcLY/0YGAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/Y6ejuR407Dy18uHO1c@2jxh3W/8MeNa05vPzQUn3NyP//o6OVDA0MDQ2UdBQMY7l0opVAHCAE8o3AfJAsBAOFjCFKQGqgGCIH0gKmQfpMYrli/xsDAA "Jelly – Try It Online").
### How?
```
SBŻ⁹¡ṫC}⁸; - Link: bits, n
S          - sum (bits) -> count of ones
 B         - to binary
    ¡      - repeat...
   ⁹       - ...times: chain's right argument = n
  Ż        - ...action: prepend a zero
             -> count of ones as binary with n leading zeros
       }   - using the right argument (n):
      C    -   complement -> 1-n
     ṫ     - tail (from 1-indexed index 1-n)
             -> parity bits (including any necessary leading zeros)
        ⁸  - chain's left argument = bits
         ; - concatenate (parity bits) to (bits)
```
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
l!n=l++cycle(mapM(:[1])$0<$[1..n])!!sum l
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0cxzzZHWzu5MjknVSM3scBXwyraMFZTxcBGJdpQTy8vVlNRsbg0VyHnf25iZp6CrUJKvgKXQkFRZl6JgopCtKGOgY4hEBrEKigqGMIkEMI6hrEwQSUlJH1wabASoF4juF4UKSA2wG4CzAokGmSOMYYbMGhcLoJZjEojGwB3EpwPdrsJktvJMgTKM4j9DwA "Haskell – Try It Online")
Input and output are lists. Test case code [from AZTECCO](https://codegolf.stackexchange.com/a/252523/20260).
Haskell doesn't have built-in binary operations, so we do things by hand. The `mapM(:[1])$0<$[1..n]` is one shorter than writing `mapM(\_->[0,1])[1..n]`, for taking the `n`-fold Cartesian product of `[0,1]`. Applying `cycle` then lets us modular index into it.
[Answer]
# [Rust](https://www.rust-lang.org), ~~120~~ 117 bytes
* -3 bytes thanks to JSorngard
```
|k:Vec<_>,m|k.iter().copied().chain((0..m).rev().map(|j|k.iter().filter(|i|**i).count()&1<<j>0)).collect::<Vec<_>>();
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVLNUsIwEJ7xyFMsOUjCxE6rHpxS8C28IMOUmo6BNjBpyoXyJF446BN48lH0acwPBaZSNW22Xza737fd2ZdXWRZq954KyGMuMIFNxhSkMIS3UqVXd59ltQgfWBJNRzSvFh5XTGLiJcsVZ08GPJs07HteTjzJ1tqVxytczY-xKc8MqHjV73OTWgqFyWUQRfORT4wjy1iiwjByOiNMBk786-IjXUrAihVqmsQFozDjqqAgWVFmigAXMO6AXnjNku5YyVKHpHFmIt3hxDWhEFBAgR_oFxHqEq3VyxK0pZ45TGideX1AyFLrx0e0owUs-e-V_efCSd1Ya8s_7BMZp1NXsids_5_WmwbDz5L-qNjasyTtyk1bpx97fHvSY9Pk_XZdsB0PLNAIuVDdlwlsLFxJLlQmuhg9ik14v0X1AJnplUU9srziMBxCL-idnUkyaJDtqdLmeJrI7dZN8G7nvt8)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes
```
{x,(y#2)\+/x}
```
[Try it online!](https://ngn.codeberg.page/k#eJyFUEFuwyAQvPMKpPZgq8QY4h4KL8ipl9xcS8EudqykJjFEworStxeMg3JKD6NdZndmNbTsalEyvdD06w3bGwBbdn0tp9+RtTCDlu/UgSe7VvRHbvnEx7S6gW2ZkJyQvOYk5XNH6sqzc+senKZ86fM8jPxaQM3XQRWxiL1iQeBnua/OsXCOTxZc8YcAwGBvzEkzjBv1LTt1bDNtRHOQttmLoZNZo37w+SK16dWgMX2nxQfBnRzkKIxcncTYm2lV90aDcjNUDMI5IIIElJ8X44gQ+D5dYiJI7/MY/NEgAMH1o0tENHuSEMEiXvjnI/4AKc5zJg==)
Takes input as a list of `0`s and `1`s (`x`) and an integer `y`.
* `+/x` the "popcnt" of the input (i.e. the number of set bits)
* `(y#2)\` "encode" the sum (using `(y#2)` guarantees the length of the result)
* `x,` append the parity bits (and implicitly return)
[Answer]
# Python, ~~44 39 65~~ 40 bytes
`m` should be a binary string, while `n` an int.
Had to add 26 bytes all because OP didn't say that 0's had to be prefixed to the parity bits, but doesn't matter since Neil found a shorter solution.
```
lambda m,n:m+bin(m.count('1')+2**n)[-n:]
```
[Answer]
# Java 8, ~~87~~ ~~73~~ 72 bytes
```
b->n->b+n.toString((n=1<<n)|n.bitCount(n.valueOf(b,2))%n,2).substring(1)
```
-14 bytes thanks to *@ceilingcat*
[Try it online.](https://tio.run/##fVDBasMwDL3nK0RgYJPExN1Oa5rLYLDD2KHHsYPdJsVZqoRaDpSt3545icfYCgPLkqWnpyc3alBZs38fd62yFp6VwY8IwJIis4PGV4Uj04ra4Y5Mh@IxBMWWTgYP6b@YJ6TqUJ1SWMBlCTVsRp2VmJU6QUHdUmAMN7IokH@i0IYeOofEUAyqddVLzXS64vwG/S2s03ZpkXwEWEdebO9068UGzUNn9nD0e7CF@/UNFJ92AqDKEotlLqcj5XcQp3DL138RPit/ZWd0PqFXV@jFrojyqSdYGJqHx8RzN4Mv0c@Hz@Ln3kU86NQgAYYFtmdL1VF0jkTvy9Qiw8QTxYlO4nvwvhaq79sz0zwEyMOQy/gF)
**Explanation:**
```
b->n->                  // Method with String & Integer parameters and String return
  b                     //  Return the given binary-String
   +                    //  Appended with:
    n.toString(         //   Convert the following integer to a (binary-)String:
      (n=1<<n)          //    1 bitwise left-shifted by `n`
                        //    (which is saved in `n` to reuse later on)
      |                 //    Bitwise-ORed by:
       n.bitCount(      //     The amount of 1-bits
        n.valueOf(b,2)) //     in the binary-String input
      %n                //    Modulo the `1<<n` we saved in variable `n`,
                        //    which is basically 2 to the power (input) `n`
      ,2)               //   (Use base-2 for the `n.toString`)
         .substring(1)  //   And remove the leading "1"
```
`n.toString(1<<length|value,2).substring(1)` is taken from [this Stackoverflow answer](https://stackoverflow.com/a/28198839/1682559).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
Ｎθη✂⍘⁺Ｘ²θΣη²±θ
```
[Try it online!](https://tio.run/##PUy7CoAwENv9CscrKNji5ubmIoV@QS2HCvVVW/3880B0SEhCEjfZ4Dbribp1T7FPy4ABDtFkOsxrhOlXxs8OobUnmsjBCNqnE/R2c18V@SGK3KSFBywUo8fRRuQrIRqiOqsqKT8wv/QaSeXlHw "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as the first input. Explanation:
```
Ｎθ
```
Input `n` as a number.
```
η
```
Print the binary message.
```
✂⍘⁺Ｘ²θΣη²±θ
```
Sum the bits in the binary message, add on `2ⁿ`, convert to binary, and print the last `n` digits.
[Answer]
# [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 149 bytes
```
N
Count b while _%52/48 {
Write _%52
_+_%52*51-2496+N
}
_+N%4
Count p while _%4 {
Count j while _%4/2*(p-j) {
Write _/52/2^(p-1-j)%2+48
}
_-_%4+N%4
}
```
Takes input as a binary string, followed by a space, followed by an integer in unary, followed by a newline. [Try it online!](https://tio.run/##S0xOTkr6/9@Pyzm/NK9EIUmhPCMzJ1UhXtXUSN/EQqGaK7woswTC54rXBlFapoa6RiaWZtp@XLVAIT9VE6jeArheE6A@iFgWQkzfSEujQDdLE2GmPtAOozigoCFQWNVI28QCZKIuUC3Y1Nr//w0MDA1hGEhCCAjHUAFEAAA "Acc!! – Try It Online")
### Explanation
```
# Read a character into the accumulator
N
# Since all the characters we'll need to handle have character codes less than 52,
# we can store the most recently read character in _%52 and the number of 1 bits
# in _/52
# While the most recent character code is >= 48 (i.e. a digit):
Count b while _%52/48 {
  # Write that digit
  Write _%52
  # Add 52 to the accumulator (i.e. add 1 to _/52) if the digit was a 1
  _+(_%52-48)*52
  # Clear the previously read character and read a new one
  _-_%52+N
}
# After reading a space, the above loop exits; _/52 is the number of 1 bits
# in the input, while _%52 is 32 from the just-read space
# In the next section, we want to distinguish among three cases:
# - Reading a 1 (code 49) means keep the loop going
# - Reading a newline (code 10) means output the parity bits
# - Reading EOF (code 0) means exit the loop
# These cases can be distinguished by taking the character code mod 4
# Read a character and add its character code mod 4 to the accumulator
_+N%4
# While accumulator mod 4 is not zero, increment p (starting from 0) and:
Count p while _%4 {
  # If accumulator mod 4 is >= 2 (meaning we just read a newline),
  # increment j (starting from 0) and loop while p-j is nonzero:
  Count j while (_%4/2)*(p-j) {
    # Write the jth parity bit, which is the bit in the 2^(p-1-j)'s place of
    # the number of 1 bits (stored in _/52)
    Write (_/52)/2^(p-1-j)%2+48
  }
  # Clear the previously read character (mod 4) and read a new one (mod 4)
  _-_%4+N%4
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
DSOIo%bI°+¦«
```
Inputs in the order \$b,n\$. Binary-I/O as strings.
[Try it online](https://tio.run/##yy9OTMpM/f/fJdjfM181yfPQBu1Dyw6t/v/fwNDQAAi5jAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H@XYP@IfNWkiEMbtA8tO7T6v87/6GglQwNDEDI0hDGUdIxjdaDiSjqGIDZYxgAoYwSTgWCoUgOQPBRDDTOAcoB6TGJjAQ).
**Explanation:**
```
D             # Duplicate the first (implicit) input binary-string
 SO           # Sum the digits of the copy
   I          # Push the second input-integer
    o         # Pop and push 2 to the power this input
     %        # Modulo the bit-sum by this
      b       # Convert it to a binary-string
       I      # Push the second input-integer again
        °     # Pop and push 10 to the power this input this time
         +    # Add it to the binary
          ¦   # Remove the leading 1
           «  # Merge the two binary-strings together
              # (after which the result is output implicitly)
```
---
If we didn't had to retain the potentially leading `0`s of input binary-strings, this could have been 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with an arithmetic addition approach:
```
Î×«DSO¹o%b+
```
Inputs in the order \$n,b\$. Binary-I/O as strings.
[Try it online](https://tio.run/##yy9OTMpM/f//cN/h6YdWuwT7H9qZr5qk/f@/EZeBoaEBEAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCceh/g4jD0w@tdgn2j8hXTdL@r/M/OtpYR8nQwBCEDA1hDKVYnWhDqDiIbQRkAzkGYAmoBggGCZiAZQ0gGGqSAZQD1BELAA).
**Explanation:**
```
Î            # Push 0 and the first input-integer
 ×           # Repeat the 0 that many times as string
  «          # Append it to the (implicit) input binary-string
   D         # Duplicate it
    SO       # Sum the digits of the copy
      ¹      # Push the first input-integer again
       o     # Pop and push 2 to the power this input
        %    # Modulo the bit-sum by this
         b   # Convert it to binary
          +  # Add the two binary strings together arithmetically
             # (after which the result is output implicitly)
```
[Answer]
# [Rust](https://www.rust-lang.org/), ~~88~~ 58 bytes
```
|a,n|format!("{a}{:0n$b}",(a.split('1').count()-1)%(1<<n))
```
[Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=634f45da728663e815bf803fe75c7469)
This closure can be assigned to a variable of type `fn(&str,usize) -> String`.
Edit: Saved 30 bytes with `split('1').count()` instead of converting to an integer, as in [Joost's](https://codegolf.stackexchange.com/users/79157/joost-k) [answer](https://codegolf.stackexchange.com/a/252607), thanks!
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 28 bytes
```
a.(J(0*,bALTB($+a)%2Eb))@>-b
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhLihKKDAqLGJBTFRCKCQrYSklMkViKSlAPi1iIiwiIiwiIiwiMDAxMTAwMTEwMDExMTEwMTExMTAxMDAxMTExMSA0Il0=)
Holy crap, this is terrible. There must be a better way to go about this. This 100% golfable.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
pUx u2pV)¤ù0V
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=cFV4IHUycFYppPkwVg&input=WzAsMCwxLDEsMCwwLDEsMSwwLDAsMSwxLDEsMSwwLDEsMSwxLDEsMCwxLDAsMCwxLDEsMSwxLDFdCjQ)
```
pUx u2pV)¤ù0V
 Ux            # Sum of the digits in U
    u   )      # Modulo:
     2pV       #   2 to the power of V
         ¤     # Convert to base 2
          ù0V  # Left-pad with 0 until the length is V
p              # Add that string to the end of U
               # Print the array with no delimiter
```
Can be modified to run without `-P` for [15 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cFV4IHUycFYppPkwVims&input=WzAsMCwxLDEsMCwwLDEsMSwwLDAsMSwxLDEsMSwwLDEsMSwxLDEsMCwxLDAsMCwxLDEsMSwxLDFdCjQ)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
pz.[\0KE.B%/z\1^2K
```
[Try it online!](https://tio.run/##K6gsyfj/v6BKLzrGwNtVz0lVvyrGMM7I@/9/AwNDQxgGkhACwjHkMgEA "Pyth – Try It Online")
### Explanation:
```
pz                    print the first input with no newline
      KE              evaluate the second input and store in K
           /z\1       number of occurrences of "1" in the first input
          %    ^2K    modulo 2 ^ K
        .B            binary representation
  .[\0K               pad with copies of "0" until length K and implicitly print
```
[Answer]
# [Desmos](https://desmos.com/calculator), 58 bytes
```
f(l,n)=join(l,mod(floor(2mod(l.total,2^n)/2^{[n...1]}),2))
```
\$f(l,n)\$ takes in a list of bits \$l\$, representing the binary message, and an integer \$n\$, representing the number of parity bits, and returns a list of bits representing the parity bits.
[Try It Online](https://www.desmos.com/calculator/hctkd9cdha)
[Try It Online - Prettified](https://www.desmos.com/calculator/knyhvb6jay)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 77 bytes
```
param($s,$n)$s
$l=($s-eq1).Count
($u=0..--$n|%{$l%2
$l=$l-shr1})[$n..1]+$u[0]
```
[Try it online!](https://tio.run/##fVHRaoMwFH33K4LcDl2NmG6vgqVssJdtrI9FinPpbLGxSyJbUb/d3aizDsYCl@TknHvuITkVn1yqjOc5TQvJW9iFVXtKZHJ0QHkgXFAW5CECyj@Y66@KUmjLgTIMfJ9SEPWsgny2MCLIqcoka9wNCN9n8RzKTRC3jWVFjkVweZFjs4CxwPYI80h/ZrY7JYMJGSC4kJ0Y5R5ZID2gXwrj1xeKboYBY02tTPdQPdlZmd343xr/fyS4mbEuqcl9Ie@SNKNPrweealJ1I/DlCAgs/nXCW/5GQgLbgdJyL96X6kHopZTJ2VCqnhF9fcannNuwtZteKbkqc438Fez@6APRyTbP61WpdHHsE8RRH8GsdZmmXCkzYQyCv0gceij2YvB3L/IuyggfDRQjfPlJM23u2MZq2m8 "PowerShell Core – Try It Online")
Takes the binary string as an int array and returns an array of ints
### Explanations
```
$s                             # Returns $s as is
$l=($s-eq1).Count              # Counts the number of ones
$u=0..--$n|%{$l%2;$l=$l-shr1}} # Gets the number as binary inverted (smallest bit on the left)
$u[$n..1]+$u[0]                # Returns the binary representation inverted. The $u[0] is to handle the case where $n=1
```
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
[,(]#2:)#:+/@[|~2^]
```
[Try it online!](https://tio.run/##dY1BC4JAFITv/oohIZNMXeukFFHQKTp0lYJFdmvD3Fq1Q4R/3ZSSVOgwb2C@9@ZdyoENg2Puw4AFF36liY31frspQ2t00D3f1P2xswxfhXc8lKam7VY2eDFcOOBSgdFUMIUrSzIai6dITpAcIrnlWRqA3XPxoHEFkUlQpcDBaZRJpbHoLL89JACp/pJ6tnMvaNKP2mz6u2n5n42Gk37S3p/V3xra9W6H2yOkfAM "J – Try It Online")
This feels golfable, but I can't for the life of me figure out where without an entirely different approach.
## Explanation
```
[,(]#2:)#:+/@[|~2^]     left: binary array. right: parity bit count
          +/@[          sum of bit array (number of 1s)
              |~        modulo
                2^]     2^parity
  (]#2:)                generate a number of 2s equal to parity bit count
        #:              and use them to convert the above quantity to base 2
                        this generates the requisite padding
[,                      concatenate them to the right of the binary array
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 46 bytes
```
v=>n=>v+(v.split`1`.length-1%2**n).toString(2)
```
[Try it online!](https://tio.run/##fY1BCoMwEEX3OUURConFmEm71Uv0AoqNaUqYiIZcPzVRXLSli8/nD483rz70yzCbyVfoHiqOTQxNi00bLjTwZbLGd9Bxq1D7ZwVnWZbIuHd3PxvUVLI4OFycVdw6TUdagAAQBaPA2Kmu8wLyweSjgJWSmdq3EOSHbMvKXg/jkS9xMu3ZiKxNnb7dtm9/oLUEiW8 "JavaScript (Node.js) – Try It Online") it was actually surprisingly easy in javascript
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 88 bytes
```
0l:3(?v1-@$"0"-:}+$10.
$1-c1.>@@:aap:2(?v$2*
?v:2%$2,:1%-ab+2.>~%1[:2(
l<0v?=gaa
>n<>r]r
```
[Try it online](https://tio.run/##NYrLCsIwEEX3@YwyAbFOmBldDW2S/xAXUfABRaSF7Oyvj4Hi4hw43Ht/LU8zmvS4S5UxQ0cd6rcHpuCA8cYh5qylfFTaA2TvUlXxIAdlj@XaS4ir53Ob3TRQTeOjFBffQ5wvs5lhPRkuRMx/mjdtwT8)
[Answer]
# [R] 92 bytes
```
fun=\(s,n)paste0(s,paste(rev(+(intToBits(nchar(gsub("0","",s))%%2^n)[1:n]==1)),collapse=""))
dat <- data.frame(s=sapply(tests, function(z) z[[1]]), n=1:4, out=outs)
dat
#                              s n                              out
# 1                        10110 1                           101101
# 2                      0110101 2                        011010100
# 3                   1011101110 3                    1011101110111
# 4 0011001100111101111010011111 4 00110011001111011110100111110010
mapply(fun, dat$s, dat$n) == dat$out
#                        10110                      0110101                   1011101110 0011001100111101111010011111 
#                         TRUE                         TRUE                         TRUE                         TRUE 
```
]