fork download
  1. import std.algorithm; // For reverse
  2.  
  3. void main() {
  4. ubyte[] littleEndian = [ 68, 135, 133, 10 ];
  5. auto bigEndian = littleEndian.dup;
  6. bigEndian.reverse();
  7.  
  8. union Fake {
  9. int i;
  10. ubyte[4] b;
  11. }
  12. Fake f;
  13.  
  14. f.i = 176_523_076;
  15. assert(f.b == littleEndian); // Machine is Little
  16.  
  17. // Little Endian data
  18. f.i = little(littleEndian);
  19. // Converts to machine native
  20. assert(f.b == littleEndian);
  21.  
  22. // Big Endian data
  23. f.i = big(bigEndian);
  24. // Converts to machine native
  25. assert(f.b == littleEndian);
  26.  
  27. ubyte[] madeBig; // Want Big Endian Here
  28. f.b = littleEndian; // first int in Little Endian
  29. madeBig = machineDependant(f.i);
  30. assert(madeBig == bigEndian); // Converted to Big Endian
  31. f.b = bigEndian; // second int in Big Endian
  32. madeBig = machineDependant(f.i);
  33. assert(madeBig == bigEndian); // Fail Convert to Big Endian
  34.  
  35. }
  36.  
  37. int little(ubyte[] data) {
  38. return (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
  39. }
  40. int big(ubyte[] data) {
  41. return (data[3]<<0) | (data[2]<<8) | (data[1]<<16) | (data[0]<<24);
  42. }
  43. ubyte[] machineDependant(int guida) {
  44. auto uuid = new ubyte[4];
  45.  
  46. uuid[0] = (guida>>24)&0xff;
  47. uuid[1] = (guida>>16)&0xff;
  48. uuid[2] = (guida>>8)&0xff;
  49. uuid[3] = (guida>>0)&0xff;
  50. return uuid;
  51. }
Runtime error #stdin #stdout 0.01s 2100KB
stdin
Standard input is empty
stdout

Standard output is empty