function [index] = binary_to_index(length,value) % binary_to_index.m % % Usage: % index = binary_to_index(5, 2) % bitstring = index_to_bitstring(index) % returns the 5 bits % bitstring = [ 0 0 0 1 0 ] % (5 bits, with binary value of 2). % Usage: % indexes = binary_to_index( [3 2 2], [7 0 2] ) % print_bitstrings(indexes) % returns % 111 % 00 % 10 % which are bitstrings of length 3, 2, 2 respectively, % with values of 7, 0, and 2 respectively. % See also INDEX_TO_BITSTRING, PRINT_BITSTRINGS, BITSTRING_TO_INDEX. % In C, I would probably use standard binary notation % with seperate length.code variables % and say something like % current_code(longest_code_length) = 0; % % Here I use Kieffer's notation, % which combines length and code into a single 'index' value. % and any other bitstring of length N % is represented by the % value of that bitstring (interpreted as standard binary) % plus the value that represents a bistring of N zeros. % Change Log: % 1999-06-25:DAV: David Cary started % Unnecessarily restrictive -- the algorithm % can handle length = 53 when value = 0 or value = 1. % IEEE754 double precision can handle integers exactly % up to (but not including) 2^53+1. See BITMAX. if( 53 <= max(length(:)) ), error('Sorry, this is too big for me to handle.') end; % ASSERT( V < 2.^L ) index = 2.^length + (value-1); % end binary_to_index.m