BigEndian.h (1939B)
1 /* 2 * Copyright 2015, Mozilla Foundation and contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef __BigEndian_h__ 18 #define __BigEndian_h__ 19 20 #include <stdint.h> 21 22 namespace mozilla { 23 24 class BigEndian { 25 public: 26 static uint32_t readUint32(const void* aPtr) { 27 const uint8_t* p = reinterpret_cast<const uint8_t*>(aPtr); 28 return uint32_t(p[0]) << 24 | uint32_t(p[1]) << 16 | uint32_t(p[2]) << 8 | 29 uint32_t(p[3]); 30 } 31 32 static uint16_t readUint16(const void* aPtr) { 33 const uint8_t* p = reinterpret_cast<const uint8_t*>(aPtr); 34 return uint32_t(p[0]) << 8 | uint32_t(p[1]); 35 } 36 37 static uint64_t readUint64(const void* aPtr) { 38 const uint8_t* p = reinterpret_cast<const uint8_t*>(aPtr); 39 return uint64_t(p[0]) << 56 | uint64_t(p[1]) << 48 | uint64_t(p[2]) << 40 | 40 uint64_t(p[3]) << 32 | uint64_t(p[4]) << 24 | uint64_t(p[5]) << 16 | 41 uint64_t(p[6]) << 8 | uint64_t(p[7]); 42 } 43 44 static void writeUint64(void* aPtr, uint64_t aValue) { 45 uint8_t* p = reinterpret_cast<uint8_t*>(aPtr); 46 p[0] = uint8_t(aValue >> 56) & 0xff; 47 p[1] = uint8_t(aValue >> 48) & 0xff; 48 p[2] = uint8_t(aValue >> 40) & 0xff; 49 p[3] = uint8_t(aValue >> 32) & 0xff; 50 p[4] = uint8_t(aValue >> 24) & 0xff; 51 p[5] = uint8_t(aValue >> 16) & 0xff; 52 p[6] = uint8_t(aValue >> 8) & 0xff; 53 p[7] = uint8_t(aValue) & 0xff; 54 } 55 }; 56 57 } // namespace mozilla 58 59 #endif // __BigEndian_h__