Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. What is best way to use 4bits for storing numbers.
Forum Updated to NodeBB v4.3 + New Features

What is best way to use 4bits for storing numbers.

Scheduled Pinned Locked Moved Unsolved C++ Gurus
3 Posts 3 Posters 669 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Q Offline
    Q Offline
    Q139
    wrote on last edited by Q139
    #1

    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?

    JonBJ 1 Reply Last reply
    0
    • Q Q139

      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?

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by JonB
      #2

      @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 a struct, 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.

      1 Reply Last reply
      1
      • fcarneyF Offline
        fcarneyF Offline
        fcarney
        wrote on last edited by
        #3

        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.

        C++ is a perfectly valid school of magic.

        1 Reply Last reply
        2

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved