Changing each value in a struct one by one

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MrPickle
    New Member
    • Jul 2008
    • 100

    Changing each value in a struct one by one

    Is there a way to go through a struct changing each value without writing it out manually, eg not doing:

    myStruct.a = 5;
    myStruct.b = 7;
    myStruct.c = 9;

    I have a struct containing 17 ints, I then read in the data from a file all at once. I then want to go through each int and convert it to little endian. I figured there's gotta be an easier way than converting all the values one by one.

    I'm using C++
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    If these ints are at all related to each other, you can have your struct contain an array of ints, and use array processing techniques to get all the data, convert it, etc.

    If this is all your struct contains, however, you have done little more than make a typedef int mystruct[17]; statement.

    Comment

    • MrPickle
      New Member
      • Jul 2008
      • 100

      #3
      I need them to have names so I can identify them, which is why they're in the struct.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by MrPickle
        I need them to have names so I can identify them, which is why they're in the struct.
        There are more ways to skin a cat; have a look:

        Code:
        struct _your_variables {
           int a, b, c, d ... q;
        }
        struct _your_struct {
           union  {
              struct _your_variables var;
              int v[17];
           } vars;
           /* other members here */
        }
        or you can name them by using the preprocessor:

        Code:
        #define A vars[0]
        #define B vars[1]
         ...
        #define Q vars[16]
        
        int vars[17];
        And there are more.

        kind regards,

        Jos

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          Personally I would say the solution is to write a function that reads the correct number of bytes from the file (which is presumably big endian) and converts that to an integer in little endian format and returns it rather than calling whatever file reading routine you are currently calling.

          If you actually read an array of bytes and then use bitwise operators (left shift and or) to construct the int then you can actually write a portable version of such a function that does not care what the endian of the current platform is.

          Comment

          Working...