473,698 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

packed datastructure - how to define?

Hi

Maybe this is a simple question, but I don't know how to solve.

Background: A weather station connected to the serial port sends data
packets. This data packets are containing variables fom one byte up to 4
byted in mixed order. Now I want to define a structure to overlay it with
UNION over the receive buffer for easily access to the single values in the
data packet.
The problem is, that I cannot defind a variable, which only reserves one
byte of memory. A simple 'char' or 'char[1]' eats 4 bytes and all following
variables are not matching.

How can I define a variable, which uses exactly one byte ?
Here is a small text app:
------------------------------------------
#include <stdio.h>
#include <stdlib.h>

struct data {
int i;
char c;
int j;
};

union ovr {
struct data d;
char c[16];
};

int main(void) {
union ovr d;
int l;

for (l=0;l<16;l++)
d.c[l]=l;

printf("size=%d \n",sizeof(d) );
printf("i=%X\n" ,d.d.i);
printf("c=%X\n" ,d.d.c);
printf("j=%X\n" ,d.d.j);
}
--------------------------------
and the output:
size=16
i=3020100
c=4
j=B0A0908

To overlay the data packet correct, j must be 8070605.
--
Jürgen
www.cfjh.de
Nov 14 '05 #1
11 3645
Hi Juergen,

Jürgen Hochwald wrote:
Maybe this is a simple question, but I don't know how to solve.

Background: A weather station connected to the serial port sends data
packets. This data packets are containing variables fom one byte up to 4
byted in mixed order. Now I want to define a structure to overlay it with
UNION over the receive buffer for easily access to the single values in the
data packet.
The problem is, that I cannot defind a variable, which only reserves one
byte of memory. A simple 'char' or 'char[1]' eats 4 bytes and all following
variables are not matching.

How can I define a variable, which uses exactly one byte ?
Here is a small text app:
------------------------------------------
#include <stdio.h>
#include <stdlib.h>

struct data {
int i;
char c;
int j;
};

union ovr {
struct data d;
char c[16];
};

int main(void) {
union ovr d;
int l;

for (l=0;l<16;l++)
d.c[l]=l;

printf("size=%d \n",sizeof(d) );
printf("i=%X\n" ,d.d.i);
printf("c=%X\n" ,d.d.c);
printf("j=%X\n" ,d.d.j);
}
--------------------------------
and the output:
size=16
i=3020100
c=4
j=B0A0908

To overlay the data packet correct, j must be 8070605.


There are several issues here:
- If you want to access something bytewise, use unsigned char
- The size of a char/signed char/unsigned char _always_ is one
byte
- A byte is not necessarily eight bit but at least so much.
Check the symbolic constant CHAR_BIT from <limits.h> to find
out the exact ratio
If you have a C99 compiler with the integer types in <stdint.h>,
then you can use the type uint8_t. 8 Bits often are referred to
as "octet"
- sizeof(int)>=si zeof(unsigned char), so your assumptions about
a certain ratio may be wrong
- In a structure, there may be padding bytes between the members
if there are alignment requirements. If sizeof(int) > 1 and
ints have to be sizeof(int)-aligned (that is, their address
can be divided by sizeof(int) without remainder), then there
are probably sizeof(int)-1 padding bytes between the c and j
members of your structure.
As an aside: If you have larger structures then it makes sense
to put the variables with the largest type first and then go
down in size -- this often leads to smaller structures.
- The bytes of types with size >1 are not necessarily ordered as
you assume. Thus,
unsigned int i=1;
unsigned char lowestbyte=((un signed char *)&i)[0];
may yield lowestbyte==1 or lowestbyte==0.

So, check the necessary size, use
union ovr {
struct data d;
unsigned char c[sizeof(struct data)];
};
or do not use a union at all but access the structure representation
directly, find out the byte order (or: rather use shifting and masking
instead of access by unsigned char for portable code), and so on.

BTW: The offsetof macro yields the offset in bytes of a member of
a structure with respect to the start of the structure.

The comp.lang.c FAQ addresses several of these issues in detail.
It has been posted here on November 1 and can also be found at
http://www.eskimo.com/~scs/C-faq/top.html
The ASCII version is up to date, unlike the HTML version.
HTH
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2

=?ISO-8859-15?Q?J=FCrgen?= Hochwald wrote:

The problem is, that I cannot defind a variable, which only reserves one byte of memory. A simple 'char' or 'char[1]' eats 4 bytes and all following variables are not matching.
No it doesn't, or it's not a C compiler. What makes you think it's
taking up more than one byte?

struct data {
int i;
char c;
int j;
};

union ovr {
struct data d;
char c[16];
};

int main(void) {
union ovr d;
int l;

for (l=0;l<16;l++)
d.c[l]=l;

printf("size=%d \n",sizeof(d) );
printf("i=%X\n" ,d.d.i);
printf("c=%X\n" ,d.d.c);
printf("j=%X\n" ,d.d.j);
}
--------------------------------
and the output:
size=16
i=3020100
c=4
j=B0A0908

Ah, it isn't the data size that is the problem, it's struct alignment.

There is no way in ISO standard C to define packed structs. Your
implementation may provide a way.


Brian

Nov 14 '05 #3
On Wed, 03 Nov 2004 22:45:19 +0100, Jürgen Hochwald <jh@cfjh.de>
wrote:
Hi

Maybe this is a simple question, but I don't know how to solve.

Background: A weather station connected to the serial port sends data
packets. This data packets are containing variables fom one byte up to 4
byted in mixed order. Now I want to define a structure to overlay it with
UNION over the receive buffer for easily access to the single values in the
data packet.
The problem is, that I cannot defind a variable, which only reserves one
byte of memory. A simple 'char' or 'char[1]' eats 4 bytes and all following
variables are not matching.

How can I define a variable, which uses exactly one byte ?
<snip>
struct data {
int i;
char c;
int j;
};
<snip>

You have the answer in your subject line, but data packing in
structures is implementation and platform dependent and off topic
here. Your compiler may have a switch or pragma to force the structure
to be packed. OTOH, your platform may not allow access of j on an odd
boundary. You might consider alternatives, such as defining an int and
copying bytes 5-8 into it. Not a robust, portable method, but it will
probably work.

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 14 '05 #4
On 3 Nov 2004 14:26:04 -0800, "Default User" <de***********@ yahoo.com>
wrote:

=?ISO-8859-15?Q?J=FCrgen?= Hochwald wrote:

The problem is, that I cannot defind a variable, which only reservesone
byte of memory. A simple 'char' or 'char[1]' eats 4 bytes and all

following
variables are not matching.


No it doesn't, or it's not a C compiler. What makes you think it's
taking up more than one byte?

The byte in the structure may be (and obviously is, in this case)
padded to align the int on a particular boundary..
struct data {
int i;
char c;
int j;
};


--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 14 '05 #5
Jürgen Hochwald wrote:
Hi

Maybe this is a simple question, but I don't know how to solve.

Background: A weather station connected to the serial port sends data
packets. This data packets are containing variables fom one byte up to 4
byted in mixed order. Now I want to define a structure to overlay it with
UNION over the receive buffer for easily access to the single values inthe
data packet.
The problem is, that I cannot defind a variable, which only reserves one
byte of memory. A simple 'char' or 'char[1]' eats 4 bytes and all following
variables are not matching.

How can I define a variable, which uses exactly one byte ?


This is Question 2.12 in the comp.lang.c Frequently
Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/faq.html

Unfortunately, the methods mentioned in the answer are
not portable (and are described as such). If you want a
portable solution, you will have to abandon the attempt
to make your program's variables match the externally-
defined format. Instead, receive the data packets into
an array of `unsigned char' and then copy the appropriate
bytes into your program's struct.

At first this may seem terribly inefficient, but it
actually is not. Your C compiler may be able to squeeze
the holes out of a struct, but there will probably be a
time penalty for every access to an unaligned field. The
penalty may be small or large (or even huge, on some kinds
of hardware), so spending a few cycles to copy the data
into a properly-aligned struct can be worth while.

Also, the copying step gives you an opportunity to
resolve things like "endian-ness" issues. If the weather
station likes to send a four-byte integer's high-order
byte first but your computer prefers to start with the
low-order byte, you would need to fiddle with the data
anyhow in order to make sense of it.

All in all, the "extra" code to reconcile the internal
and external format is seldom wasteful and often useful.

--
Er*********@sun .com

Nov 14 '05 #6

Alan Balmer wrote:
On 3 Nov 2004 14:26:04 -0800, "Default User" <de***********@ yahoo.com> wrote:

No it doesn't, or it's not a C compiler. What makes you think it's
taking up more than one byte?

The byte in the structure may be (and obviously is, in this case)
padded to align the int on a particular boundary..

So, that doesn't have anything to do with the OP's contention that he
can't define a data type of size 1.

You also snipped my further remark, after he listed the struct size:
Ah, it isn't the data size that is the problem, it's struct

alignment.

Brian

Nov 14 '05 #7
On 3 Nov 2004 15:21:46 -0800, "Default User" <de***********@ yahoo.com>
wrote:

Alan Balmer wrote:
On 3 Nov 2004 14:26:04 -0800, "Default User"<de*********** @yahoo.com>
wrote:

>No it doesn't, or it's not a C compiler. What makes you think it's
>taking up more than one byte?
>
>

The byte in the structure may be (and obviously is, in this case)
padded to align the int on a particular boundary..

So, that doesn't have anything to do with the OP's contention that he
can't define a data type of size 1.


That was not his contention, as was obvious in the context which you
snipped.
You also snipped my further remark, after he listed the struct size:
> Ah, it isn't the data size that is the problem, it's struct

alignment.

And realizing that later, you didn't go back and edit your first
impulse?

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 14 '05 #8

Alan Balmer wrote:
And realizing that later, you didn't go back and edit your first
impulse?

Why didn't you?

Brian

Nov 14 '05 #9
On 3 Nov 2004 16:04:21 -0800, "Default User" <de***********@ yahoo.com>
wrote:

Alan Balmer wrote:
And realizing that later, you didn't go back and edit your first
impulse?

Why didn't you?


I don't edit your writing unless you pay me to do so.

End of thread, afaic.

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3657
by: Santosh | last post by:
Hello, I would like some input on choosing a datastructure and a algorithm. I have a text file which contains three strings(say name, phonenumber and city). The file contains a about a billion records. I need to choose a datastructure which will sort efficienctly based on any of the strings(keys) which may be any one of the three or a combination of the three in which case we will need to sort with multiple keys.
6
1841
by: Muralidhar | last post by:
Hi all, I saw in one function that its return type was written as PACKED...I wasnt sure what that would mean. Any pointers on this? Also, what is the significance of specifically mentioning the LOCAL to a function definition when it will be a local function without the access of its declaration? Thanks
56
10447
by: ccwork | last post by:
Hi all, Here is a sample code segment: .... typedef PACKED struct { union { PACKED struct { char red:1;
3
3847
by: Amaryllis | last post by:
Hi again, I'm new to the world of communicating between VB.NET and AS/400, so I've been posting a lot of questions lately since no one else in the company has done anything like this before. Hopefully, this one is fairly simple. I'm trying to insert records into a table on the 400. I can insert into a packed field that has no decimal places and into the alphanumeric fields as well. Everything seems to translate except the values that...
3
7372
by: Brian Henry | last post by:
Does anyone know of or know how to convert a COBOL packed decimal in a text file to a decimal that .NET can work with? we are importing Old COBOL data files that have packed data in them and need to convert it to a form we can use. thanks!
3
12139
by: parag.kanade | last post by:
I have a packet structure which has a field of Integer arrays, that is packed struct { int a; char b; int count; }foo; I need to initialize all the entries of count to a particular value,
15
23971
by: Daniel Rudy | last post by:
What is the difference between packed and unpacked structs? -- Daniel Rudy Email address has been base64 encoded to reduce spam Decode email address using b64decode or uudecode -m Why geeks like computers: look chat date touch grep make unzip
8
1962
by: Philippe Martin | last post by:
Hi, Is it possible to define a packed C structure in python and pass it to the c module, or should the wrapper do that ? Regards, Philippe
9
17617
by: Sikandar | last post by:
Hi, I am beginner in C. Pls let me know what is packed array in C. Where is it used? Thanks, Sikandar
0
8674
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9028
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8895
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7728
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4369
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.