473,797 Members | 2,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Four or Two Bytes?

Does anybody know the answer to the following? An unsigned short is 2
bytes long. Why is the following file created as 4 bytes instead of
2?

file = fopen("data.bin ", "wb");
if (file != NULL)
{
unsigned short s = 65535;
printf("Size of unsigned short: %d bytes\n", sizeof(unsigned
short)); // 2 bytes - OK
fwrite(&s, sizeof(unsigned short), sizeof(s), file);
fclose(file); // File written as 4 bytes... hmm
}

- Hahnemann

Jun 27 '08
33 1832
Keith Thompson wrote:
"Joachim Schmitz" <no*********@sc hmitz-digital.dewrite s:
>pete wrote:
[...]
This entire discussion is about as close to having no practical
meaning as I can imagine. An implementation that had as many padding
bits for unsigned short as we're talking about, or even as many value
bits, would be beyond exotic; it would be clinically insane.
We were discussing the DS9K.

--
pete
Jun 27 '08 #31
"Barry Schwarz" <sc******@dqel. comwrote in message
news:68******** *************** *********@4ax.c om...
On Thu, 29 May 2008 22:53:32 -0400, "Bill Leary" <Bi********@msn .com>
wrote:
>>"Hahnemann" <ha************ *@gmail.comwrot e in message
news:2f****** *************** *************@d 1g2000hsg.googl egroups.com...
>>Does anybody know the answer to the following? An unsigned short is 2
bytes long. Why is the following file created as 4 bytes instead of
2?

file = fopen("data.bin ", "wb");
if (file != NULL)
{
unsigned short s = 65535;
printf("Size of unsigned short: %d bytes\n", sizeof(unsigned
short)); // 2 bytes - OK
>> fwrite(&s, sizeof(unsigned short), sizeof(s), file);

fwrite(
pointer to buffer ... ok
size of an element of that buffer ... 2
number of elements to write ... 2
handle for file write should occur to ... ok

So, 2 elements of 2 bytes each should write four bytes.
>> fclose(file); // File written as 4 bytes... hmm

So, fwrite worked correctly. More or less, since it wrote out 4 bytes
from
a 2 byte object. It could just about as easily have crashed when it went
beyond the bounds of the object.

Actually, fwrite invoked undefined behavior and only appeared to work
correctly because the OP was using it on a system where he was allowed
to access memory beyond the end of s. On a well-behaved system (tm),
his program would have been interrupted in an implementation defined
manner.
Sure. But since the specific question was why he got four bytes rather than
two in the target file I emphasized that 2 * 2 is 4, and alluded your point
by commenting "More or less..." and mentioning the crash.

- Bill

Jun 27 '08 #32
On Sun, 1 Jun 2008 19:56:33 -0400, "Bill Leary" <Bi********@msn .com>
wrote:
>"Barry Schwarz" <sc******@dqel. comwrote in message
news:68******* *************** **********@4ax. com...
snip
>Actually, fwrite invoked undefined behavior and only appeared to work
correctly because the OP was using it on a system where he was allowed
to access memory beyond the end of s. On a well-behaved system (tm),
his program would have been interrupted in an implementation defined
manner.

Sure. But since the specific question was why he got four bytes rather than
two in the target file I emphasized that 2 * 2 is 4, and alluded your point
by commenting "More or less..." and mentioning the crash.
But once the OP has invoked undefined behavior, there is no guarantee
that 2*2 will still equal 4. The only reason fwrite produced 4 bytes
is that this particular manifestation of undefined behavior produced 4
bytes. The fact that he inadvertently asked for 4 bytes is only
unfortunate coincidence. The next time it executes it could do
something completely different. If the OP were to recompile with
different options, who knows what the code could do.
Remove del for email
Jun 27 '08 #33
"Barry Schwarz" <sc******@dqel. comwrote in message
news:1t******** *************** *********@4ax.c om...
On Sun, 1 Jun 2008 19:56:33 -0400, "Bill Leary" <Bi********@msn .com>
wrote:
>>Sure. But since the specific question was why he got four bytes rather
than
two in the target file I emphasized that 2 * 2 is 4, and alluded your
point
by commenting "More or less..." and mentioning the crash.

But once the OP has invoked undefined behavior, there is no guarantee
that 2*2 will still equal 4. The only reason fwrite produced 4 bytes
is that this particular manifestation of undefined behavior produced 4
bytes. The fact that he inadvertently asked for 4 bytes is only
unfortunate coincidence. The next time it executes it could do
something completely different. If the OP were to recompile with
different options, who knows what the code could do.
You are both technically and theoretically correct.

The root issue, however, was that he was telling the function to write four
bytes when he thought he was telling it to write two bytes.

Explaining the potentially world shattering side effects* of what might have
happened due to his misunderstandin g invoking "undefined behavior" would
hardly have been profitable. What he needed, and asked for, was an
explanation of what actually did happen.

If you want to go on in the "undefined behavior" vein, please do so.
Someone has to fight the Good Fight, and you seem to understand your topic
well and do it with great verve.**

For me, I'm done.

- Bill
______________
* I recall someone in another "undefined behavior" thread saying that the
program was free to do anything at all, including implode the world, if it
so desired.
** Yeah, I'm being a little sarcastic. But just a little. I've just
re-examined a half dozen messages where you made your "undefined behavior"
spiel and in each of them (as far as I could tell) you were dead on correct.
An impressive accomplishment.

Jun 27 '08 #34

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

Similar topics

9
2266
by: William S. Huizinga | last post by:
I've got an array.array of unsigned char and would like to make a slice of that array (e.g. a) become one long like I would in "C" : l = ((unsigned long *) (&a)); I have been getting what I want in this sort of manner : l = 0L l = a l += a << 8
11
5226
by: fivelitermustang | last post by:
Actually, how would I go about allocating a four-dimensional dynamic array? I only know how to make two dimensional dynamic arrays: double **v; v = new double*; for (int i=0; i<C; i++) { v = new double; }
1
1769
by: Chris Lutka | last post by:
I've been racking my brains all day over this. And I'm not the best at SQL either. I need a query that will produce the following results: Product,Warehouse,Sold_LastYear,Sold_ThisYear,Sold_3Months,Sold_MTD I've got four queries to give me the Sold_* fields. Their fields are Product, Warehouse, and Units. I also have a table which these queries originated from. The table UV_SPPROD (I didn't name it) has Product, Warehouse, Period...
19
5887
by: Lorenzo J. Lucchini | last post by:
My code contains this declaration: : typedef union { : word Word; : struct { : byte Low; : byte High; : } Bytes; : } reg;
1
2473
by: les | last post by:
If all are unsigned integers, then why not make it easy on yourself and just multiply each by a scaler to effect the shift? ie each position is just multiplied by 128^n-1 byte1 + byte2*128 + byte3 *(128 *128) + byte4 * (128 * 128 *128) >-----Original Message-----
6
2200
by: lovecreatesbeauty | last post by:
/* It seems that when an int with width of four bytes is assigned to a one byte width char, the first three bytes from left to right are discarded and the rightest byte is assigned to that char. So, I can just assign an int to a char to retrieve the rightest byte of that int, and I also use this method plus right-shift operation to get the leftest byte of an int.
0
9536
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10468
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
10245
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
10205
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
10021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9063
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...
0
6802
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5458
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.