Register union equivalent?

Hi, in C, I can link pointers towards several data type to the same data like this:

register union {
   char  *charptr;
   int   *intptr;
   float *floatptr;
   short *shortptr;
   } allptr;

char buffer[400];
inptr=fopen(argv[argc-1],"r");
itest=fread(buffer,1,400,inptr);
allptr.charptr=buffer;

*allptr.shortptr++ = 3; % example

I would like to do the same in Octave. Create an array of bytes (char or char I guess) then modify the bytes at certain locations as I see fit using various format types: int16, int32 etc …

Do you know a quick way to do so ?

What I am really trying to do is create a buffer of int8 of 400 elements and write the bytes of int32 or int16 starting at a user defined index between 1 and 400…

Thanks.

OSX 12.4
GNU Octave Version: 7.2.0 (hg id: 6c1e310b2230)
GNU Octave License: GNU General Public License
Operating System: Darwin 21.5.0 Darwin Kernel Version 21.5.0:

Where are you writing this to? A file? If so, do fread and fwrite serve your needs? You can specify size and precision with them, like 400*int8=>int32 or similar. Binary I/O (GNU Octave (version 7.2.0))

I’m thinking of something like this: read 400 bytes, change one or more of them (can’t think of a union but I normally use bitmasks for changing bitwidths), then write to file specifying size and precision using fwrite.

I’m not sure if I understand what you are trying to do. But maybe typecast is what you are looking for?

Yes, I could do that. Multiple fwrite but it would be slow.
What I could do is to make a template to file using multiple fwrite then read the file back as int32 to , use repmat to make bigger matrixes, then modify the int32 values I want before final fwrite.

I looked into typecast, bitpack and bitunpack and I think I can make it happen.
Thanks for the pointer (pun intended) !

the problem I was facing is that I was writing the data BIG ENDIAN to disk. So I had to compensate for the swap done by fwrite in uint32 bits for the positions of all my int16 values …
I used bitunpack to put the little endian values where I wanted in the vector. Then I used typecast to convert to an int16 vector, modified the position to compensate for BIG ENDIAN and used typecast of the int16 vector to feed fwrite ! But now, it is fast and I have one fwrite to do instead of hundreds …
Thanks all of you again, this was very fun.

1 Like