Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Storing 2 bytes in one

Storing 2 bytes in one

Scheduled Pinned Locked Moved C#
databasetutorial
24 Posts 7 Posters 0 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.
  • C Offline
    C Offline
    Chris Copeland
    wrote on last edited by
    #1

    Hey, i've been looking for an effective method of storing 2 byte values within one. Or, two short values within one. The system I currently use is by embedding an unsafe code to point to a byte value and to cast the relevant data. Here's an example:

    byte db, v1, v2;
    v1 = 50;
    v2 = 80;

    unsafe
    {
    byte* db_p = &db;
    db_p[0] = (byte)((v1) >> 2);
    db_p[1] = (byte)(((v1) << 6) | (((v2) >> 4)&0x3F));
    db_p[2] = (byte)((v2) << 4);
    }

    Which stores two values excellently. However, For values below 4 generally, numbers tend to overlap each other. IE, values of v1 = 0, v2 = 0; and v1 = 1, v2 = 1; tend to have the same digit value of db. I was wondering there were any other methods of storing 2 values of data (bytes) within one single data (I'm using this to remove the necessity for multi-dimensional arrays and large collection objects). Thank you!

    L L J P V 6 Replies Last reply
    0
    • C Chris Copeland

      Hey, i've been looking for an effective method of storing 2 byte values within one. Or, two short values within one. The system I currently use is by embedding an unsafe code to point to a byte value and to cast the relevant data. Here's an example:

      byte db, v1, v2;
      v1 = 50;
      v2 = 80;

      unsafe
      {
      byte* db_p = &db;
      db_p[0] = (byte)((v1) >> 2);
      db_p[1] = (byte)(((v1) << 6) | (((v2) >> 4)&0x3F));
      db_p[2] = (byte)((v2) << 4);
      }

      Which stores two values excellently. However, For values below 4 generally, numbers tend to overlap each other. IE, values of v1 = 0, v2 = 0; and v1 = 1, v2 = 1; tend to have the same digit value of db. I was wondering there were any other methods of storing 2 values of data (bytes) within one single data (I'm using this to remove the necessity for multi-dimensional arrays and large collection objects). Thank you!

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      1. this isn't C# code is it? hence: wrong forum. 2. db_p is a pointer pointing to a byte, yet you write at locations db_p+0, db_p+1, db_p+2, so you write past the item your pointer points to, which is either not allowed (C#) or cheating (C/C++). 3. Of course you can store 2 byte values in 3 bytes; it is plain stupid. X|

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


      I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


      C 1 Reply Last reply
      0
      • L Luc Pattyn

        1. this isn't C# code is it? hence: wrong forum. 2. db_p is a pointer pointing to a byte, yet you write at locations db_p+0, db_p+1, db_p+2, so you write past the item your pointer points to, which is either not allowed (C#) or cheating (C/C++). 3. Of course you can store 2 byte values in 3 bytes; it is plain stupid. X|

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


        I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


        C Offline
        C Offline
        Chris Copeland
        wrote on last edited by
        #3

        Well i'm sorry but i'm not entirely experienced with the whole "storing two values in one". I came here asking for help, not asking to be told i'm stupid and the methods i'm using are stupid.. That post didn't help at all, does anyone else have any real experience in storing data values inside one variable? Thanks

        L 1 Reply Last reply
        0
        • C Chris Copeland

          Hey, i've been looking for an effective method of storing 2 byte values within one. Or, two short values within one. The system I currently use is by embedding an unsafe code to point to a byte value and to cast the relevant data. Here's an example:

          byte db, v1, v2;
          v1 = 50;
          v2 = 80;

          unsafe
          {
          byte* db_p = &db;
          db_p[0] = (byte)((v1) >> 2);
          db_p[1] = (byte)(((v1) << 6) | (((v2) >> 4)&0x3F));
          db_p[2] = (byte)((v2) << 4);
          }

          Which stores two values excellently. However, For values below 4 generally, numbers tend to overlap each other. IE, values of v1 = 0, v2 = 0; and v1 = 1, v2 = 1; tend to have the same digit value of db. I was wondering there were any other methods of storing 2 values of data (bytes) within one single data (I'm using this to remove the necessity for multi-dimensional arrays and large collection objects). Thank you!

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          No offense, but your code is odd. Now of course you can store multiple values in one variable, but they'll be smaller. Example:

          static byte CombineBytes(byte a, byte b)
          {
          return (byte)((a & 15) | (b << 4));
          }

          A and B can only be zero through 15 though, obviously. To get them back:

          byte a = (byte)(x & 15);
          byte b = (byte)(x >> 4);

          warning: all code here is untested. (but really it is just about the idea, not the actual code)

          C 1 Reply Last reply
          0
          • C Chris Copeland

            Hey, i've been looking for an effective method of storing 2 byte values within one. Or, two short values within one. The system I currently use is by embedding an unsafe code to point to a byte value and to cast the relevant data. Here's an example:

            byte db, v1, v2;
            v1 = 50;
            v2 = 80;

            unsafe
            {
            byte* db_p = &db;
            db_p[0] = (byte)((v1) >> 2);
            db_p[1] = (byte)(((v1) << 6) | (((v2) >> 4)&0x3F));
            db_p[2] = (byte)((v2) << 4);
            }

            Which stores two values excellently. However, For values below 4 generally, numbers tend to overlap each other. IE, values of v1 = 0, v2 = 0; and v1 = 1, v2 = 1; tend to have the same digit value of db. I was wondering there were any other methods of storing 2 values of data (bytes) within one single data (I'm using this to remove the necessity for multi-dimensional arrays and large collection objects). Thank you!

            J Offline
            J Offline
            J4amieC
            wrote on last edited by
            #5

            Just out of interest; why would you want to do this?

            C 1 Reply Last reply
            0
            • J J4amieC

              Just out of interest; why would you want to do this?

              C Offline
              C Offline
              Chris Copeland
              wrote on last edited by
              #6

              Well, I plan on having a 2D plain with cells ranging from 15x15 to up to 300x300, and rather than using a library collection storing both values, I would prefer to have both values point to an index within an array. IE, R1C1 => Index 1, R1C2 => Index 2 etc etc.. I have read that these are possible but with no solutions.

              L B 2 Replies Last reply
              0
              • L Lost User

                No offense, but your code is odd. Now of course you can store multiple values in one variable, but they'll be smaller. Example:

                static byte CombineBytes(byte a, byte b)
                {
                return (byte)((a & 15) | (b << 4));
                }

                A and B can only be zero through 15 though, obviously. To get them back:

                byte a = (byte)(x & 15);
                byte b = (byte)(x >> 4);

                warning: all code here is untested. (but really it is just about the idea, not the actual code)

                C Offline
                C Offline
                Chris Copeland
                wrote on last edited by
                #7

                Thank you for this. Let's say I want to store a value greater than 15, would it be plausable to use a "short" value instead, to increase the available range of data? And, would each of the values produced be unique, or would they intersect at some point with conflicting values? Thank you for your help.

                L 1 Reply Last reply
                0
                • C Chris Copeland

                  Well, I plan on having a 2D plain with cells ranging from 15x15 to up to 300x300, and rather than using a library collection storing both values, I would prefer to have both values point to an index within an array. IE, R1C1 => Index 1, R1C2 => Index 2 etc etc.. I have read that these are possible but with no solutions.

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  Seriously? Do you mean: index = x + y * width That's pretty much basic knowledge.. so I suspect you mean something else, but then what do you mean?

                  C 1 Reply Last reply
                  0
                  • C Chris Copeland

                    Thank you for this. Let's say I want to store a value greater than 15, would it be plausable to use a "short" value instead, to increase the available range of data? And, would each of the values produced be unique, or would they intersect at some point with conflicting values? Thank you for your help.

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #9

                    It just divided the byte in two parts, you could do the same with a short (then you could fit in two complete bytes) or an int (then you could fit in 2 complete shorts or 4 bytes) But if you want a 2D -> 1D mapping it's better to use something "sane" such as x + y * width or if you don't want to use width you could use morton numbers to get a Z curve (just interleave the bits of your indices)

                    1 Reply Last reply
                    0
                    • L Lost User

                      Seriously? Do you mean: index = x + y * width That's pretty much basic knowledge.. so I suspect you mean something else, but then what do you mean?

                      C Offline
                      C Offline
                      Chris Copeland
                      wrote on last edited by
                      #10

                      Well, let's say each cell has a corresponding slot in an array containing information about the cell. Each cell, when clicked or managed, will refer to the single slot in an array corresponding to the co-ordinates or row,column values. If I was to use a method that relies on adding or multiplying x and y, there are chances that two cell coordinates may intersect and point to the same object. Therefore, I need the mathematical formula that produces an output using x and y to be a unique index key (not too large, otherwise the array would consume considerable amounts of memory), so that it may point to a slot in the array of cell information. 1,1 => Slot 1 in the array 1,2 => Slot 2 in the array 2,1 => Different slot than '1,2'. Thank you :)

                      L 1 Reply Last reply
                      0
                      • C Chris Copeland

                        Well, let's say each cell has a corresponding slot in an array containing information about the cell. Each cell, when clicked or managed, will refer to the single slot in an array corresponding to the co-ordinates or row,column values. If I was to use a method that relies on adding or multiplying x and y, there are chances that two cell coordinates may intersect and point to the same object. Therefore, I need the mathematical formula that produces an output using x and y to be a unique index key (not too large, otherwise the array would consume considerable amounts of memory), so that it may point to a slot in the array of cell information. 1,1 => Slot 1 in the array 1,2 => Slot 2 in the array 2,1 => Different slot than '1,2'. Thank you :)

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #11

                        Yes that's why you multiply y by the width

                        C 1 Reply Last reply
                        0
                        • L Lost User

                          Yes that's why you multiply y by the width

                          C Offline
                          C Offline
                          Chris Copeland
                          wrote on last edited by
                          #12

                          I'm confused about what the value of 'width' should be. If width is the size of the cell, then I get conflicting types. When I ran a debug loop doing (x + y * 16) I received conflicts at 17,1 17,2 etc etc. And if I use 300 as the width, then the size of the array will be equal to 90,300 which is rediculously massive. Considering each slot in the array will store a structure of information, that could be quite a massive amount of memory usage?

                          L 1 Reply Last reply
                          0
                          • C Chris Copeland

                            I'm confused about what the value of 'width' should be. If width is the size of the cell, then I get conflicting types. When I ran a debug loop doing (x + y * 16) I received conflicts at 17,1 17,2 etc etc. And if I use 300 as the width, then the size of the array will be equal to 90,300 which is rediculously massive. Considering each slot in the array will store a structure of information, that could be quite a massive amount of memory usage?

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #13

                            The width of the 2D grid, if your coordinate goes up to 17 then either your width is >= 18 or your x coordinate it out of bounds (in that case it's only normal that it conflicts, it just wrapped to the next row) Edit: if you don't have a width (if your grid is essentially infinite) then you can still use morton numbers.

                            C 1 Reply Last reply
                            0
                            • L Lost User

                              The width of the 2D grid, if your coordinate goes up to 17 then either your width is >= 18 or your x coordinate it out of bounds (in that case it's only normal that it conflicts, it just wrapped to the next row) Edit: if you don't have a width (if your grid is essentially infinite) then you can still use morton numbers.

                              C Offline
                              C Offline
                              Chris Copeland
                              wrote on last edited by
                              #14

                              I see, i'm sorry if I sound stupid i'm just not used to trying to store parameters like these. So, say I have a 300x300 map, would the formula be [x + y * 300]? Using this method, the value of the cell at 300 + 300 * 300 = 90,300. Would it be better to use bit-wise operations to try and reduce the total value down to a small index, or is this getting too complicated? If need be, I will simply have to make a collection of structures, and make each object key equal to "x,y". Although I would prefer to avoid using any forms of collections, and focus more on indexing values on the 2D map

                              L 1 Reply Last reply
                              0
                              • C Chris Copeland

                                I see, i'm sorry if I sound stupid i'm just not used to trying to store parameters like these. So, say I have a 300x300 map, would the formula be [x + y * 300]? Using this method, the value of the cell at 300 + 300 * 300 = 90,300. Would it be better to use bit-wise operations to try and reduce the total value down to a small index, or is this getting too complicated? If need be, I will simply have to make a collection of structures, and make each object key equal to "x,y". Although I would prefer to avoid using any forms of collections, and focus more on indexing values on the 2D map

                                L Offline
                                L Offline
                                Lost User
                                wrote on last edited by
                                #15

                                Epoque wrote:

                                So, say I have a 300x300 map, would the formula be [x + y * 300]?

                                Yes. edit: note that the coordinate 300,300 is out of bounds in both directions, a 300x300 map only goes up to 299,299

                                Epoque wrote:

                                Would it be better to use bit-wise operations to try and reduce the total value down to a small index, or is this getting too complicated?

                                There is no reliable way to do that unless your grid is sparse in a specific and known way (in other words: probably not) If all your cells are used, the x + y * width formula will have an efficiency of 100% (it will number all w*h cells from 0 to w*h-1 with no gaps, so it can not be improved upon)

                                1 Reply Last reply
                                0
                                • C Chris Copeland

                                  Well i'm sorry but i'm not entirely experienced with the whole "storing two values in one". I came here asking for help, not asking to be told i'm stupid and the methods i'm using are stupid.. That post didn't help at all, does anyone else have any real experience in storing data values inside one variable? Thanks

                                  L Offline
                                  L Offline
                                  Luc Pattyn
                                  wrote on last edited by
                                  #16

                                  when I said "storing 2 byte values in 3 bytes is plain stupid." I can assure you it is, as that isn't compression at all, if anything it is expansion.

                                  Epoque wrote:

                                  i'm not entirely experienced with the whole "storing two values in one"

                                  Nobody is, as it can't be done. If you could store two byte values in one byte (i.e. store two byte values and then retrieve those values in any order and as often as you'd like), then what would keep you from doing that recursively: you could store the first two bytes of anything in 1, the next two bytes in another one, then combine those two bytes into a final byte; in the end you could store any amount of data, why not the entire Internet, into that one final byte? We do get lunatics asking such questions regularly. OTOH one of the replies you posted earlier in this thread seems to indicate an entirely different problem: storing one (or N) values for a 2D collection of cells. That can easily be solved in many ways: 1. with N two-dimensional arrays 2. with N one-dimensional arrays, and linearizing the index (as in index = x + y * width) 3. with a single one-dimensional array holding a little struct, which holds the different values for a single cell. If that is what you need, then you should have made that clear from the start. :)

                                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                  I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


                                  1 Reply Last reply
                                  0
                                  • C Chris Copeland

                                    Hey, i've been looking for an effective method of storing 2 byte values within one. Or, two short values within one. The system I currently use is by embedding an unsafe code to point to a byte value and to cast the relevant data. Here's an example:

                                    byte db, v1, v2;
                                    v1 = 50;
                                    v2 = 80;

                                    unsafe
                                    {
                                    byte* db_p = &db;
                                    db_p[0] = (byte)((v1) >> 2);
                                    db_p[1] = (byte)(((v1) << 6) | (((v2) >> 4)&0x3F));
                                    db_p[2] = (byte)((v2) << 4);
                                    }

                                    Which stores two values excellently. However, For values below 4 generally, numbers tend to overlap each other. IE, values of v1 = 0, v2 = 0; and v1 = 1, v2 = 1; tend to have the same digit value of db. I was wondering there were any other methods of storing 2 values of data (bytes) within one single data (I'm using this to remove the necessity for multi-dimensional arrays and large collection objects). Thank you!

                                    P Offline
                                    P Offline
                                    PIEBALDconsult
                                    wrote on last edited by
                                    #17

                                    I don't see why you're using an unsafe context to do that. And you basically can't store sixteen bits in an eight-bit byte.

                                    L 1 Reply Last reply
                                    0
                                    • C Chris Copeland

                                      Well, I plan on having a 2D plain with cells ranging from 15x15 to up to 300x300, and rather than using a library collection storing both values, I would prefer to have both values point to an index within an array. IE, R1C1 => Index 1, R1C2 => Index 2 etc etc.. I have read that these are possible but with no solutions.

                                      B Offline
                                      B Offline
                                      Ben Fair
                                      wrote on last edited by
                                      #18

                                      It seems you are essentially looking for a Hashing algorithm to take 2 values and create a single unique value where the hash would be unique across your entire set; for example the hash of the values 14, 16 would need to be different than 16, 14. I would recommend using one of the built-in collection classes that implement such algorithms rather than trying to create your own. The Hashtable and Dictionary classes should work nicely or you can use the System.Drawing.Point class to create coordinates. Personally, I'd use Dictionary where the Points are X, Y coordinates of the cells in the set. Since Point is a struct its operated on as a value type and can easily lend itself to what you're trying to do. I believe the default Point struct's X and Y members are int and if you are worried about wasted memory you could create your own Point struct that has X and Y of byte, or short, etc. If you decide to use the Dictionary class try to pass in the number of cells to the constructor (you will hopefully know that upon creation) and it will help performance slightly by preventing it from automatically growing its internal collection as items are added.

                                      Hope in one hand and poop in the other; see which fills up first. Hope and change were good slogans, now show us more than words.

                                      L 1 Reply Last reply
                                      0
                                      • B Ben Fair

                                        It seems you are essentially looking for a Hashing algorithm to take 2 values and create a single unique value where the hash would be unique across your entire set; for example the hash of the values 14, 16 would need to be different than 16, 14. I would recommend using one of the built-in collection classes that implement such algorithms rather than trying to create your own. The Hashtable and Dictionary classes should work nicely or you can use the System.Drawing.Point class to create coordinates. Personally, I'd use Dictionary where the Points are X, Y coordinates of the cells in the set. Since Point is a struct its operated on as a value type and can easily lend itself to what you're trying to do. I believe the default Point struct's X and Y members are int and if you are worried about wasted memory you could create your own Point struct that has X and Y of byte, or short, etc. If you decide to use the Dictionary class try to pass in the number of cells to the constructor (you will hopefully know that upon creation) and it will help performance slightly by preventing it from automatically growing its internal collection as items are added.

                                        Hope in one hand and poop in the other; see which fills up first. Hope and change were good slogans, now show us more than words.

                                        L Offline
                                        L Offline
                                        Lost User
                                        wrote on last edited by
                                        #19

                                        No offense but that's a really bad idea if all he wants to do is map 2D coordinates to 1D coordinates..

                                        J 1 Reply Last reply
                                        0
                                        • P PIEBALDconsult

                                          I don't see why you're using an unsafe context to do that. And you basically can't store sixteen bits in an eight-bit byte.

                                          L Offline
                                          L Offline
                                          Luc Pattyn
                                          wrote on last edited by
                                          #20

                                          yet another non-believer. :doh:

                                          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                          I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups