0

I wrote the following code which cast a long long to a byte array.

BYTE Buffer[8 +32];
BYTE * Temp = reinterpret_cast<BYTE*> (&Size);
Buffer[0] = Temp[0]; Buffer[1] = Temp[1]; Buffer[2] = Temp[2]; Buffer[3] = Temp[3]; 
Buffer[4] = Temp[4]; Buffer[5] = Temp[5]; Buffer[6] = Temp[6]; Buffer[7] = Temp[7];
//The next 32 bytes (Buffer[8] to Buffer[39]) contains the file name.
WriteFile(hFile,Buffer,40,&dwWrite,NULL);

Now the question is Is it safe to cast an int64 directly into bytes ? What are the possible bugs ?

I am well aware of other safer methods to do this (Bitshifting for example) but i want the code to be as fast as possible.

Thanks !

HMVC
  • 99
  • 1
  • 11

1 Answers1

1

Problem is you write to disk with the byte ordering of the current machine. If you read it again on a machine with different byte ordering you will run into big trouble.

Thats why bit shifting would be the better way to do it.

Ole Dittmann
  • 1,764
  • 1
  • 14
  • 22
  • Even if the machines run on windows ? because this code is intended to run on windows only. – HMVC Jan 25 '14 at 15:31
  • Yes, even for Windows the byte odering is not defined. It depends on the Processor type. But, well of course in practice nearly all Windows run on an Intel-Processor and therefore have high-endian byte ordering – Ole Dittmann Jan 25 '14 at 15:34
  • Unless you take Windows for ARM into account: http://stackoverflow.com/questions/6449468/can-i-safely-assume-that-windows-installations-will-always-be-little-endian – Remy Lebeau Jan 25 '14 at 18:19
  • So i can safely assume that Windows x86/x64 will always be little-endian ? – HMVC Jan 25 '14 at 22:32
  • "little-endian" yes, you are right. The naming is quite confusing :-). But anyway I would not rely on that, who says that next year there will not be a new processor "en vogue" and then your program would not work any more. It nearly happened once with the so called "Power-PC"s. – Ole Dittmann Jan 26 '14 at 01:06