type-punning

Safely punning char* to double in C

In an Open Source program I wrote, I'm reading binary data (written by another program) from a file and outputting ints, doubles, and other assorted data types. One of the challenges is that it needs to run on 32-bit and 64-bit machines of both endiannesses, which means that I end up having to do quite a bit of low-level bit-twiddling. ...

Opinions on type-punning in C++?

I'm curious about conventions for type-punning pointers/arrays in C++. Here's the use case I have at the moment: Compute a simple 32-bit checksum over a binary blob of data by treating it as an array of 32-bit integers (we know its total length is a multiple of 4), and then summing up all values and ignoring overflow. I would expect...

Reassemble float from bytes inline

I'm working with HiTech PICC32 on the PIC32MX series of microprocessors, but I think this question is general enough for anyone knowledgable in C. (This is almost equivalent to C90, with sizeof(int) = sizeof(long) = sizeof(float) = 4.) Let's say I read a 4-byte word of data that represents a float. I can quickly convert it to its actual...

Java: Using type punning on primitive arrays?

Hello, everyone! I need to be able to convert byte arrays to/from other primitive type arrays, but instead of casting, I need type punning. Correct term for raw copy without casting? I thought it would be possible to do the following: // idea: byte[12] -> int[3], and int[3] -> byte[12] int[] ints; ByteBuffer bb = ByteBuffer.wrap( ...

Purpose of Unions in C and C++

I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code union ARGB { uint32_t colour; struct componentsTag { uint8_t b; uint8_t g; uint8_t r; uint8_t a; } components; } pixel; pixel.colour = 0xff040201; /* ---- somewhere down the...

Compile time float packing/punning

I'm writing C for the PIC32MX, compiled with Microchip's PIC32 C compiler (based on GCC 3.4). Added The standard I'm following is GNU99 (C99 with GNU extensions, compiler flag -std=gnu99) My problem is this: I have some reprogrammable numeric data that is stored either on EEPROM or in the program flash of the chip. This means that when...

Redundant __packed__ attributes

This code is for Microchip's PIC32MX microprocessor. Their compiler is essentially GCC 3.4. I tend use GCC's __packed__ attribute to pack bitfields into a union, and later retrieve them as an unsigned char (ie. type-punning) for sending over SPI or I2C. This behaviour is all defined by my implementation, and works perfectly. I prefer th...

Analysis of C code

Hello! Here is function that i am writing on 64 bit linux machine. void myfunc(unsigned char* arr) //array of 8 bytes is passed by reference { unsigned long a = 0; //8 bytes unsigned char* LL = (unsigned char*) &a; LL[0] = arr[6]; LL[1] = arr[3]; LL[2] = arr[1]; LL[3] = arr[7]; LL[4] = arr[5]; LL[5] = arr[4]; ...