Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   C: Converting types while keeping same size. (http://www.go4expert.com/forums/c-converting-types-keeping-size-t4591/)

sbho 7Jun2007 14:01

C: Converting types while keeping same size.
Hi all.
This is my first post here. I need urgent help. I have a deadline to meet and i am stuck on this stupid problem.
Basically i am implementing my own virtual file system. I need to store data on it, raw data, about files and stuff. The problem is if i have a structure of 512 bytes, i need to store it on the virtual disk with size of 512 bytes. I can read from and write to the disk character buffers. I need to store the structure on the disk. But this structure has ints and char* s.
If i convert the ints to chars i get larger overall buffer which can't fit in a 512 bytes on disk.

So is there any way i can convert the struct to a char*, keeping the ints to 4 bytes characters. Actually they are unsigned shorts (2 bytes). So it's like i need to read 1 byte from the short and convert it to char and then read the other byte. (then convert back when filling the structure).

Thanks alot, guys!

DaWei 7Jun2007 16:59

Re: C: Converting types while keeping same size.
Structs usually align their members on natural boundaries. This is often determined by the size of an int. Some systems can address off of natural boundaries and will allow you to pack the struct. See your compiler documentation for how to specify that. It's often a pragma. Systems that can't address off a natural boundary will give you a bus fault if you try.

The easy way to do it, regardless of packing, is to transfer each member individually. In that way, the information occupies only the amount of spaced actually used. Since a disk is a byte-oriented device, no alignment is necessary.

For a virtual disk, however, you may still have the memory alignment problems. Off-boundary byte operations such as the transfer of individual chars are handled, when necessary, by the hardware. This may involve reading multiple bytes from the destination, replacing a byte, and writing the multiple bytes back. This only has to occur, at worst, at the two ends of the transfer, in order to achieve alignment. The remainder are transferred in aligned groups.

I think you'll need to treat the destination as a 512-byte char array and transfer each struct member by casting it to char and transferring it as a char array to the desired index in the destination array.

drop2kumar 8Jun2007 07:16

Re: C: Converting types while keeping same size.
If you are facing Structure padding problem then you can use #pragma pack(1) in your program,so that only 512 bytes will be stored in your disk

DaWei 8Jun2007 07:31

Re: C: Converting types while keeping same size.
....if your compiler/system supports that (as mentioned in the first paragraph of my response). Not all do.

All times are GMT +5.5. The time now is 12:45.