diff --git a/libavcodec/common.c b/libavcodec/common.c
index dadaf5df4245c4104552e5d6d6c0183f350afe07..97788ec9dc2596f33d784ec6a0bf61d3dda8656a 100644
--- a/libavcodec/common.c
+++ b/libavcodec/common.c
@@ -174,6 +174,9 @@ unsigned int get_bits_long(GetBitContext *s, int n)
                 (buf_ptr[-2] << 8) |
                 (buf_ptr[-1]);	    
 #endif
+            val |= bit_buf >> (32 + bit_cnt);
+            bit_buf <<= - bit_cnt;
+            bit_cnt += 32;
         } else {
             buf_ptr -= 4;
             bit_buf = 0;
@@ -185,11 +188,13 @@ unsigned int get_bits_long(GetBitContext *s, int n)
                 bit_buf |= *buf_ptr++ << 8;
             if (buf_ptr < s->buf_end)
                 bit_buf |= *buf_ptr++;
+
+            val |= bit_buf >> (32 + bit_cnt);
+            bit_buf <<= - bit_cnt;
+            bit_cnt += 8*(buf_ptr - s->buf_ptr);
+            if(bit_cnt<0) bit_cnt=0;
         }
         s->buf_ptr = buf_ptr;
-        val |= bit_buf >> (32 + bit_cnt);
-        bit_buf <<= - bit_cnt;
-        bit_cnt += 32;
     }
     s->bit_buf = bit_buf;
     s->bit_cnt = bit_cnt;