Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

for the C guru's...

Options
  • 30-01-2002 2:35pm
    #1
    Registered Users Posts: 1,259 ✭✭✭


    say i have an integer 12345 and i want to place it in an octet array ( occupying 2 octets ). can i just do the following or is there a better way?

    int myInt = 12345;
    byte octetArray[ 10 ];

    octetArray[ 1 ] = myInt;
    // does the above place the 8 least significant bits of myInt into
    // the array

    octetArray[ 0 ] = myInt >> 8;
    //same thing except with the next 8 bits of myInt;

    any ideas anyone?
    Alb


Comments

  • Closed Accounts Posts: 9,314 ✭✭✭Talliesin


    octetArray[ 1 ] = myInt

    Is a pretty ugly implicit cast.

    octetArray[1] = (byte) myInt at least makes the cast more explicit.

    octetArray[1] = (byte) (myInt & 0xFF) makes the cast and the truncation explict.

    Similarly:

    octetArray[ 0 ] = (byte) ((myInt >> 8) & 0xFF)

    I'm assuming that the value in myInt will always be in a two byte range, or you only care about the two least significatn bytes, check this assumption holds for your code.

    You may have explict memory copying functions available to from libraries (I don't know if there is one in the standard, but the Windows API has CopyMemory and similar provided by the kernel). This is of little value here, where you are just moving two bytes, but can be extremely efficient for larger ranges (for one thing they probably use assembly memory copying operations that are faster than anything that could be expressed in unoptomised pure C).


  • Closed Accounts Posts: 9,314 ✭✭✭Talliesin


    I don't know if there is one in the standard, but the Windows API has CopyMemory and similar provided by the kernel

    Ah, I remember now. C library function memcpy will copy blocks of memory.

    void* memcpy(void* dest, const void* src, size_t count);

    Which would be horribly obscure for moving 2 bytes like this, but is useful elsewhere. There are variations for things like copying overlapped regions, stopping if a particular byte was copied, etc.


  • Closed Accounts Posts: 411 ✭✭Jay


    !!! You got there just before me... I was just going to say to use memcpy().....

    shot.


  • Registered Users Posts: 1,259 ✭✭✭alb


    Talliesin, cheers. That's just the info I was looking for and though it works correctly with the explicit casting, the implicit are clearer I guess.

    I do use memcpy for large amounts of data but it would be completely overkill here for 2 octet's worth.

    Thanks,
    Alb


Advertisement