// I have an existing array of bytes that I transmit between 2 Arduinos using I2C. byte ArrayOfBytes[193]; // I need to read the bytes from a double and add them to a specific location in the existing array. const int SpecificLocation = 37; double foo = 123.456; void loop1() {   for (size_t i = 0… Answer from johnwasser on forum.arduino.cc
🌐
Cplusplus
cplusplus.com › forum › beginner › 85527
Double to Byte - C++ Forum
November 20, 2012 - FWIW, using unions that way is unsupported (and undefined) by the C++ standard and therefore is not guaranteed to work - even though most compilers tend to implement them that way. ... I guess using pointers requires less code - just a bit more knowledge achieving the same thing. ... Here is what I ended up doing. It works perfectly! WORD cells; cells = (WORD)NumberOfCells; sendCANindexedbytes[1] = (BYTE)cells; sendCANindexedbytes[2] = (BYTE)(cells >> 8); Thanks for the help! ... I think he was talking about a double-byte word.
🌐
Bytes
bytes.com › home › forum › topic › c sharp
How to Convert double to bytes? - Post.Byes
August 12, 2023 - I already knew how to convert bytes[] to Double, use BitConverter.To Double().
Discussions

c++ - How to convert a byte array into double in C? - Stack Overflow
I've got a byte array containing 8 bytes and would like to convert and use them as a double precision binary floating-point number. Could someone please tell me how to convert it? More on stackoverflow.com
🌐 stackoverflow.com
c++ - Convert between double and byte array, for transfer over ZigBee API? - Stack Overflow
I'm trying to take two doubles (GPS coordinates) and send them over the ZigBee API to another ZigBee receiver unit, but I don't know how to decompose the doubles into byte arrays and then re-compose them back into their original form once they are transferred. More on stackoverflow.com
🌐 stackoverflow.com
c++ double to byte array - Stack Overflow
I want to cast double numbers to byte array (unsigned char*) std::vector v; for (int i = 0; i More on stackoverflow.com
🌐 stackoverflow.com
August 6, 2014
c - Set a double to byte array - Stack Overflow
what's a fast way of assigning a double to 8 bytes inside a byte array? I have a byte array that is about 4k bytes big and I am attempting to take 8 bytes out of that and copy it into a double. I am More on stackoverflow.com
🌐 stackoverflow.com
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Double to byte array - Programming - Arduino Forum
July 14, 2018 - I have an existing array of bytes that I transmit between 2 Arduinos using I2C. I need to read the bytes from a double and add them to a specific location in the existing array. At the receiving end I need to convert the…
Top answer
1 of 5
4

std::vector<unsigned char*> is a vector (list) of pointers to unsigned char. This is not what you want.

I guess you want to have std::vector<unsigned char> (no pointers here).

For each number you want to add to the list, you have to add several (typically 8) bytes to it. In order to do it, the simplest method is:

const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&a);
for (size_t i = 0; i < sizeof(double); ++i)
    v.push_back(ptr[i]);

To extract a number from such an array of bytes:

for (int i = 0; i < v.size(); i++) {
    double number;
    memcpy(&number, &v.at(i * sizeof(double)), sizeof(double));
    std::cout << number << std::endl;
}
2 of 5
1

This is really wrong you are saving pointers to address that would be out of scope (a and b), this would cause invalid memory access (would work as you expected OR would not).

You are declaring a vector of pointer (std::vector<unsigned char*>) not a vector of unsigned char (std::vector<unsigned char>).

According to the output of this sample, it appear as if GCC (version 4.9.0) it reusing the same memory for variables a and b in the loop OR extracted away the variables of the loop. Because it prints only two different address of the pointer storage in the vector.

#include <vector>
#include <iostream>

int main() {
    std::vector<unsigned char*> v;

    for (int i = 0; i < 5; i++) {

        double a = 3.14 + i;
        double b = 4.44 + i;

        v.push_back((unsigned char*)&a);
        v.push_back((unsigned char*)&b);
    }

    for (int i = 0; i < v.size(); i++) {
        std::cout << std::hex << ((double*)v.at(i)) << std::dec << std::endl;
        std::cout << *((double*)v.at(i)) << std::endl;
    }
}

Output:

0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
🌐
Answers
answers.com › computers › How_many_bytes_for_double_in_c
How many bytes for double in c? - Answers
October 16, 2024 - In C, a double typically occupies 8 bytes (64 bits) of memory. This size can vary depending on the platform and compiler, but the C standard specifies that a double must provide at least as much precision as a float and is often implemented ...
Find elsewhere
🌐
Global Tech Council
globaltechcouncil.org › home › blogs › what is double in c?
What is Double in C? - Global Tech Council
April 22, 2026 - Float uses 4 bytes, while double uses 8 bytes. Double provides greater precision. It is preferred for complex calculations. Double can represent numbers from approximately 1.7E-308 to 1.7E+308. This wide range makes it useful.
🌐
C# Corner
c-sharpcorner.com › uploadfile › mahesh › convert-double-to-byte-array-in-C-Sharp
Convert Double to Byte Array in C#
February 8, 2010 - The BitConverter class in .NET Framework is provides functionality to convert base data types to an array of bytes, and an array of bytes to base data types. The BitConverter class has a static overloaded GetBytes method that takes an integer, double or other base type value and convert that to a array of bytes.
Top answer
1 of 9
31

Easiest is to make a union:

#include <stdio.h>

int main(void) {
  int ii;
  union {
    float a;
    unsigned char bytes[4];
  } thing;

  thing.a = 1.234;
  for (ii=0; ii<4; ii++) 
    printf ("byte %d is %02x\n", ii, thing.bytes[ii]);
  return 0;
}

Output:

byte 0 is b6
byte 1 is f3
byte 2 is 9d
byte 3 is 3f

Note - there is no guarantee about the byte order… it depends on your machine architecture.

To get your function to work, do this:

void float2Bytes(byte bytes_temp[4],float float_variable){ 
  union {
    float a;
    unsigned char bytes[4];
  } thing;
  thing.a = float_variable;
  memcpy(bytes_temp, thing.bytes, 4);
}

Or to really hack it:

void float2Bytes(byte bytes_temp[4],float float_variable){ 
  memcpy(bytes_temp, (unsigned char*) (&float_variable), 4);
}

Note - in either case I make sure to copy the data to the location given as the input parameter. This is crucial, as local variables will not exist after you return (although you could declare them static, but let's not teach you bad habits. What if the function gets called again…)

2 of 9
14

Here's a way to do what you want that won't break if you're on a system with a different endianness from the one you're on now:

byte* floatToByteArray(float f) {
    byte* ret = malloc(4 * sizeof(byte));
    unsigned int asInt = *((int*)&f);

    int i;
    for (i = 0; i < 4; i++) {
        ret[i] = (asInt >> 8 * i) & 0xFF;
    }

    return ret;
}

You can see it in action here: http://ideone.com/umY1bB

The issue with the above answers is that they rely on the underlying representation of floats: C makes no guarantee that the most significant byte will be "first" in memory. The standard allows the underlying system to implement floats however it feels like -- so if you test your code on a system with a particular kind of endianness (byte order for numeric types in memory), it will stop working depending on the kind of processor you're running it on.

That's a really nasty, hard-to-fix bug and you should avoid it if at all possible.

🌐
GitHub
gist.github.com › caot › 3b80a430c3155cd0032f
byte array from / to double [ c++ vs java ] · GitHub
byte array from / to double [ c++ vs java ]. GitHub Gist: instantly share code, notes, and snippets.
Top answer
1 of 4
4

Building a float or double character-by-character can cause a trap representation so don't do that. Replace the _arr definition with std::array<char, Size> _arr; and then use in.read + std::memcpy:

Example:

#include <cstring> // std::memcpy
// writer:
std::array<char, Size> _arr;

bool convert_num(T inp) {
    static_assert(sizeof(T) == sizeof(value_t),
                    "T and value_t need to be the same size");
    std::memcpy(_arr.data(), &inp, Size);
    return true;
}

bool write(std::ostream& outfile) {
    return static_cast<bool>(outfile.write(_arr.data(), Size));
}
// reader:
std::array<char, Size> _arr;

bool add_nums(std::istream& in) {
    return static_cast<bool>(in.read(_arr.data(), Size));
}

bool convert() {
    std::memcpy(&outp, _arr.data(), Size);
    return true;
}

Demo (originally from Paddy)

2 of 4
2

The main issue with your program is the shifting of a smaller data type when you read. You have this in two places (shown together here for clarity, despite being out of context):

outp += ((uint8_t)(*begin) << (i * 8));
outp += ((*begin) << (i << 3));

In both these cases, the iterator begin references an underlying type of int8_t. Not only is this a signed type, but you're placing trust in the compiler to promote the type to a large enough integer. I actually ran into a similar issue some years ago.

See here: Undefined high-order of uint64_t while shifting and masking 32-bit values

The fix is to cast to the correct size before shifting:

outp += (((value_t)(uint8_t)*begin) << (i * 8));
outp += (((value_t)(uint8_t)*begin) << (i << 3));

I would also like to suggest that you avoid using constructs like i << 3 instead of i * 8. There is simply no need to try and be clever. The compiler will do the right thing, and you're just making the code harder to read. It also lacks consistency, since you're using both forms in the same function.

🌐
TutorialKart
tutorialkart.com › c-programming › c-double-data-type
C double Data Type - Storage Size, Examples, Min and Max Values
February 20, 2025 - It allows storing real numbers with higher precision compared to the float data type and is commonly used for mathematical computations that require greater accuracy. The storage size of the double data type is typically 8 bytes (64 bits), though ...
🌐
C# Corner
c-sharpcorner.com › UploadFile › mahesh › convert-byte-array-to-double-in-C-Sharp
How to Convert a Byte Array to Double in C#
September 14, 2018 - The BitConverter class in .NET Framework provides functionality to convert base datatypes to an array of bytes, and an array of bytes to base data types. The BitConverter class has a static overloaded GetBytes method that takes an integer, double or other base type value and converts that to an array of bytes.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
8 Bytes to Double Conversion - Programming - Arduino Forum
January 28, 2022 - Howdy All.. hopefully someone will be able to help me. I have the following byte array: byte vals[] = { 0xC6, 0x6B, 0x80, 0xE8, 0x69, 0xF5, 0xB0, 0x3F }; and I need to convert that that to a double or a decimal equivalent for example: 1.6345634542 How can I accomplish this? Thanks in advance..
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-language › type-double
Type double | Microsoft Learn
August 3, 2021 - You can try changing directories. ... Double precision values with double type have 8 bytes. The format is similar to the float format except that it has an 11-bit excess-1023 exponent and a 52-bit mantissa, plus the implied high-order 1 bit.