0

In 7 bits, given a number store the number's content as long as the number is one of the following: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

First of all, is this possible?

I am not looking for code but for a design advice, eg store 1 in the 1st bit in this case, 0 in this case etc.

edit: This is used in a compression algorithm. In case the above is not possible, try to fit the number given we have on our hands the prev number and the prev number is 1, 2, 3, ... 10

Luka
  • 1,761
  • 2
  • 19
  • 30

2 Answers2

3

You only need four bits to store the numbers 1 through 10:

0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = 8
1001 = 9
1010 = 10

There's background material on this encoding at https://en.wikipedia.org/wiki/Binary_number.

Chris Culter
  • 4,470
  • 2
  • 15
  • 30
  • 1
    +1 Wish you had mentioned the range of 3 bits is 8, and 4 bits is 16. – Elliott Frisch Jan 17 '14 at 04:58
  • 1
    An addendum, you may want to check out 'bitfields', a non-portable but commonly used way to perform bit-packing of values. [A good discussion on SO here](http://stackoverflow.com/questions/1044654/bitfield-manipulation-in-c) – Jake H Jan 17 '14 at 05:00
  • 1
    @ElliottFrisch Well, then you have to mention the difference between 0..7 and 1..8, and "why can't you just subtract the endpoints", and now we're talking about fencepost errors, and it might be a bit much for someone seeing the concept for the first time. Maybe the question asked about 1..10 precisely because 3 bits is clearly too few, and 4 bits is clearly enough, so one doesn't have to worry about the exact bounds just yet. (But I have no idea why the question asked about 7 bits!) – Chris Culter Jan 17 '14 at 05:09
  • 1
    @JakeHeidt: bit fields are generally portable at the usual source code level... just the memory layout / padding / ordering is more prone to variation across environments (compilers, systems etc) than for most types. – Tony Delroy Jan 17 '14 at 05:56
  • Curious - why did you start with '0001' when he only has to store 1-10? Surely `0000 = 1`, `0001 = 2`, ... `1001 = 10` – kfsone Jan 17 '14 at 06:05
  • @kfsone Yep, both encodings work. The binary numeral encoding is easier to describe and more widely used, so I defaulted to it. – Chris Culter Jan 17 '14 at 06:24
2
0 : 0000000
1 : 0000001
2 : 0000010
3 : 0000011
4 : 0000100
5 : 0000101
6 : 0000110
7 : 0000111
8 : 0001000
9 : 0001001
10: 0001010

Unless I misunderstood your question, that should work.

R Sahu
  • 204,454
  • 14
  • 159
  • 270