Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wonder if there is an utility to read and print a (binary) file, shifted by some amount of bits (i mean, it should accept amounts, which are not divisible by 8).

.. something like dd (and its skip option), but bit-wise, instead of byte-wise.

(If you think that there is no such thing, and are going to implement it here, please use C.. i have my own bit-shifting thing for strings, written in Python, but it is surely relatively slow as hell)

share|improve this question

migrated from superuser.com Nov 15 '12 at 2:46

This question came from our site for computer enthusiasts and power users.

Are you really asking for bit shifting? It sounds more like you're looking to strip bits rather than shift them... – Chris Down Nov 15 '12 at 2:51
Chris: really, shifting. that dd example might be little confusing.. – mykhal Nov 15 '12 at 8:20
up vote 3 down vote accepted

Try this:

#include <stdio.h>
#include <stdlib.h>

#define SIZE (1024*1024)

int main (int argc, char *argv[])
  FILE *from = fopen(argv[1], "rb");
  FILE *to = fopen(argv[2], "wb");
  int nbits = atoi(argv[3]);
  int offs_bytes = nbits/8;
  int shift_bits = nbits%8;
  unsigned char *buf = malloc(SIZE);
  size_t res, pos, i;

  for (pos=0; pos<offs_bytes; pos++)
    buf[pos] = 0;

  buf[pos++] = 0;

  while ((res = fread(buf+pos, 1, SIZE-pos, from))) {
    for (i=0; i < res; i++) {
      buf[pos-1] |= (buf[pos] >> shift_bits) & 0xFF;
      buf[pos] = buf[pos] << (8 - shift_bits);
    fwrite(buf, 1, pos-1, to);
    buf[0] = buf[pos-1];
    pos = 1;
  fwrite(buf, 1, 1, to);
  fclose(from); fclose(to);
  return 0;

(Simple algorithm, no error checking, barely tested, etc... [usual caveats]).

share|improve this answer
looks promising.. just hunt some bugs.. unfrotunately, it's adding a zero byte after every SIZE bytes – mykhal Nov 15 '12 at 13:22
Sorry. Typical off-by-1 error. Try it now. – angus Nov 15 '12 at 13:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.