What is best way to use 4bits for storing numbers.
-
Hi,
I would like to assign values 1-15 using something like half char , 4bits instead of 8 char to compress data.For calculations probably need to use char.
What would be best method for just using half bits of char and packing it sequentially to memory?
-
Hi,
I would like to assign values 1-15 using something like half char , 4bits instead of 8 char to compress data.For calculations probably need to use char.
What would be best method for just using half bits of char and packing it sequentially to memory?
@Q139
These 4 bits are called a "nibble" :) Just store 2 of them in each byte/char to pack into smallest space. Use bit-shift operators & mask to put them in/pull the out. Or, you may (well) prefer to use "bit field packing" in astruct
, https://en.cppreference.com/w/c/language/bit_field, for nicer support, and have the compiler do the manipulations for you, but it's essentially the same thing. Your code will be "slower" because of pack/unpack. but will occupy smaller space. -
https://en.cppreference.com/w/cpp/language/bit_field
Get familiar with this site. It contains just about everything with really good explanations of C and C++. It also has an offline copy you can download.