473,890 Members | 1,885 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reading a double var byte per byte

Hi,
is it possible to read a double variable one byte at a time.
I would want store each byte into unsigned char and then assemble again
the double variable again.

thanx

Andrea
Nov 14 '05
15 3613
jeko wrote:

Hi,
is it possible to read a double variable one byte at a time.
I would want store each byte into unsigned char
and then assemble again
the double variable again.


/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
const double source = 3.14159265;
double destination;
size_t byte;
unsigned char array[sizeof destination];

byte = sizeof array;
while (byte-- != 0) {
array[byte] = ((unsigned char *)&source)[byte];
}
byte = sizeof array;
while (byte-- != 0) {
((unsigned char *)&destination )[byte] = array[byte];
}
printf("source is %f\n", source);
printf("destina tion is %f\n", destination);
return 0;
}

/* END new.c */

--
pete
Nov 14 '05 #11
Pierre Maurette <ma************ @wanadoo.fr> wrote:
jeko a écrit :
[...]
About union: is correct touse unsigned char vector when union is
intialized with a double? On the Kernighan Manual this is an incorrect use. I don't know. Maybe not 100% standard compliant.


100% not Standard compliant, rather.
But is "store each byte [of a double variable] into unsigned char" a
standard compliant question ?


Yes.

Richard
Nov 14 '05 #12
Pierre Maurette wrote:

jeko a écrit :
[...]
About union: is correct touse unsigned char vector when union is
intialized with a double? On the Kernighan Manual this is an incorrect use. I don't know. Maybe not 100% standard compliant.


#include <stdio.h>

int main(void)
{
union
{
double d;
unsigned char uca[sizeof(double)];
} u;
size_t i;
u.d = 3.1415926;

printf("The object representation of %f is ", u.d);

for(i = 0; i < sizeof u.uca; i++)
{
printf("%02X", u.uca[i]);
}
printf("\n\nSee 6.2.6.1(4) of C99.\n");

return 0;
}
But is "store each byte [of a double variable] into unsigned char" a
standard compliant question ?


If you mean "does it make sense within the context of the C language
to ask about getting at the bytes of a double via some technique
involving unsigned chars?", then the answer is yes, it does.
Nov 14 '05 #13
On Tue, 18 Jan 2005 16:01:14 +0100, Pierre Maurette wrote:
jeko a écrit :
Hi,
is it possible to read a double variable one byte at a time.
I would want store each byte into unsigned char and then assemble again
the double variable again. Maybe:
int i;
union {
double f;
unsigned char ftab[sizeof(double)];
}double_bytes;


Using unions for this sort of thing is always iffy, it is the wrong tool
for the job. You can do this more simply and with no questionmarks over
correctness using pointers, e.g.

int main(void)
{
double d = 0.1;
unsigned char *p = (unsigned char *)&d;
int i;

for (i = 0; i < sizeof d; i++)
printf(" %02x", (unsigned)p[i]);

putchar('\n');

return 0;
}
double_bytes.f = 123.54;

for(i = 0; i < sizeof(double); ++i)
{
printf("%d\t", double_bytes.ft ab[i]);
}
}
for(i = 0; i < sizeof(double); ++i)
{
double_bytes.ft ab[i] = 0;
}
}
printf("\n%f\n" , double_bytes.f) ;


This is dangerous, C doesn't guarantee that all-bits-zero is a valid
representation for a double. Also while C's type aliasing rules allow
accessing any object as an array of character type (where unsigned char is
the useful one), it doesn't guarantee that an array of character type can
be accessed as a double. Doing this in a union makes the situation more
complex, but not clearly correct.

Lawrence


Nov 14 '05 #14
Richard Bos wrote:

jeko <a.*********@fa stwebnet.it> wrote:
Pierre Maurette ha scritto:
jeko a écrit :

> is it possible to read a double variable one byte at a time.
> I would want store each byte into unsigned char and then assemble
> again the double variable again.

Maybe:
Definitely, however...
int i;
union {
double f;
unsigned char ftab[sizeof(double)];
}double_bytes;


...this is not the solution. Once you've assigned a value to one union
member, the values of all others become undefined (or was it
unspecified? Unreliable, in any case).
but how copy double into unsigned char vector?


There's no such thing as "vectors" in C (unless you create a
user-defined type or alias with that name, of course). What Pierre uses
is an array.

The proper solution is either this:

double d=123.456;
unsigned char *ptr;

for (ptr=(unsigned char *)&d; ptr<=(unsigned char *)(d+1); ptr++) {
/* Do something with the next byte, i.e. *ptr, for example: */
printf("%u\n", *ptr); /* Note no cast: integer conversions again. */
}


It should be
ptr != (unsigned char *)(&d+1)
instead of
ptr<=(unsigned char *)(d+1)

--
pete
Nov 14 '05 #15
Pierre Maurette <ma************ @wanadoo.fr> writes:
jeko a écrit :
[...]
Ok,
but how copy double into unsigned char vector?
In your code initialize only the vector with 0 value.

Maybe the problem is my english ;-)
(my italian is worse).
But:

double any_float = 123.456;
union {
double f;
unsigned char ftab[sizeof(double)];
}double_bytes;
double_bytes.f = any_float;

initialize the vector double_bytes.ft ab[] with any_float bytes, no ?


That should work. You can also use memcpy():

#include <stdio.h>
#include <string.h>

int main(void)
{
double d0 = 123.456;
unsigned char buf[sizeof(double)];
double d1;

memcpy(buf, &d0, sizeof(double)) ;
memcpy(&d1, buf, sizeof(double)) ;

printf("d0 = %f\nd1 = %f\n", d0, d1);

return 0;
}

Output:

d0 = 123.456000
d1 = 123.456000

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #16

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

Similar topics

8
9540
by: Yeow | last post by:
hello, i was trying to use the fread function on SunOS and ran into some trouble. i made a simple test as follows: i'm trying to read in a binary file (generated from a fortran code) that contains the following three floating-point numbers: 1.0 2.0 3.0
22
3729
by: bq | last post by:
Hello, Two questions related to floating point support: What C compilers for the wintel (MS Windows + x86) platform are C99 compliant as far as <math.h> and <tgmath.h> are concerned? What wintel compilers support a 16-byte "long double" (with 33 decimal digits of accuracy) including proper printf() support. I found some compilers that did support "long double", but theirs was an 8-byte or 10-byte or 12-byte type with accuracy the...
3
2622
by: RoSsIaCrIiLoIA | last post by:
I have rewrote the malloc() function of K&R2 chapter 8.7 typedef long Align; ^^^^ Here, should I write 'long', 'double' or 'long double'? I know that in my pc+compiler sizeof(long)=4, sizeof(double)=8 and sizeof(long double)=10 (if 'long' or 'double' sizeof(Header)=8 if 'long double' sizeof(Header)=12)
9
6795
by: jeff M via .NET 247 | last post by:
I'm still having problems reading EBCDIC files. Currently itlooks like the lower range (0 to 127) is working. I have triedthe following code pages 20284, 20924, 1140, 37, 500 and 20127.By working I get the correct answer by taking the decimal valueand using that as an index to an array that will map to thecorrect EBCDIC value in hex. By larger values, an example would be "AA" in EBCDIC hex wouldgive me the value of 63 in decimal (ASCII) when...
6
5283
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
11
3604
by: Freddy Coal | last post by:
Hi, I'm trying to read a binary file of 2411 Bytes, I would like load all the file in a String. I make this function for make that: '-------------------------- Public Shared Function Read_bin(ByVal ruta As String) Dim cadena As String = "" Dim dato As Array If File.Exists(ruta) = True Then
5
6647
by: anders.weitman | last post by:
Hi! I want to get the representation in memory of a variable of type double and put it in an array of four unsigned short int (I'm on a 32- bits Windows architecture so a double is 64-bits and an unsigned short int is 16-bits). For example, the double precision representation of 1/3 is 3fd5 5555 5555 5555 (hex).
13
1545
by: cmdolcet69 | last post by:
I have this code below that will open a created file and read the file to the end. However if my file has values 200,300,400 seperated by commas how can i read in each seperate value and place it into an arraylist? I need to do some sort of commas split to just read the values and not the commas. Dim oFile As File Dim oRead As System.IO.StreamReader Dim EntireFile As String
4
2677
by: knuckels23 | last post by:
Hi All, I have a Random access file which is written using VB 6.0. I need to read this file using C#. The record used in VB to write the Random access file is as follows Type AA aa1 As Integer aa2 As Integer aa3 As Integer aa4 As Integer
0
9975
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...
1
10899
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
10446
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
9614
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
8004
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
7154
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
6032
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4255
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3263
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.