1*0afa8e06SEd Maste /* 2*0afa8e06SEd Maste * Copyright (c) 2020 Yubico AB. All rights reserved. 3*0afa8e06SEd Maste * Use of this source code is governed by a BSD-style 4*0afa8e06SEd Maste * license that can be found in the LICENSE file. 5*0afa8e06SEd Maste */ 6*0afa8e06SEd Maste 7*0afa8e06SEd Maste #include "openbsd-compat.h" 8*0afa8e06SEd Maste 9*0afa8e06SEd Maste #if defined(_WIN32) && !defined(HAVE_ENDIAN_H) 10*0afa8e06SEd Maste 11*0afa8e06SEd Maste /* 12*0afa8e06SEd Maste * Hopefully, if the endianness differs from the end result, the compiler 13*0afa8e06SEd Maste * optimizes these functions with some type of bswap instruction. Or, 14*0afa8e06SEd Maste * otherwise, to just return the input value unmodified. GCC and clang 15*0afa8e06SEd Maste * both does these optimization at least. This should be preferred over 16*0afa8e06SEd Maste * relying on some BYTE_ORDER macro, which may or may not be defined. 17*0afa8e06SEd Maste */ 18*0afa8e06SEd Maste 19*0afa8e06SEd Maste uint32_t 20*0afa8e06SEd Maste htole32(uint32_t in) 21*0afa8e06SEd Maste { 22*0afa8e06SEd Maste uint32_t out = 0; 23*0afa8e06SEd Maste uint8_t *b = (uint8_t *)&out; 24*0afa8e06SEd Maste 25*0afa8e06SEd Maste b[0] = (uint8_t)((in >> 0) & 0xff); 26*0afa8e06SEd Maste b[1] = (uint8_t)((in >> 8) & 0xff); 27*0afa8e06SEd Maste b[2] = (uint8_t)((in >> 16) & 0xff); 28*0afa8e06SEd Maste b[3] = (uint8_t)((in >> 24) & 0xff); 29*0afa8e06SEd Maste 30*0afa8e06SEd Maste return (out); 31*0afa8e06SEd Maste } 32*0afa8e06SEd Maste 33*0afa8e06SEd Maste uint64_t 34*0afa8e06SEd Maste htole64(uint64_t in) 35*0afa8e06SEd Maste { 36*0afa8e06SEd Maste uint64_t out = 0; 37*0afa8e06SEd Maste uint8_t *b = (uint8_t *)&out; 38*0afa8e06SEd Maste 39*0afa8e06SEd Maste b[0] = (uint8_t)((in >> 0) & 0xff); 40*0afa8e06SEd Maste b[1] = (uint8_t)((in >> 8) & 0xff); 41*0afa8e06SEd Maste b[2] = (uint8_t)((in >> 16) & 0xff); 42*0afa8e06SEd Maste b[3] = (uint8_t)((in >> 24) & 0xff); 43*0afa8e06SEd Maste b[4] = (uint8_t)((in >> 32) & 0xff); 44*0afa8e06SEd Maste b[5] = (uint8_t)((in >> 40) & 0xff); 45*0afa8e06SEd Maste b[6] = (uint8_t)((in >> 48) & 0xff); 46*0afa8e06SEd Maste b[7] = (uint8_t)((in >> 56) & 0xff); 47*0afa8e06SEd Maste 48*0afa8e06SEd Maste return (out); 49*0afa8e06SEd Maste } 50*0afa8e06SEd Maste 51*0afa8e06SEd Maste #endif /* WIN32 && !HAVE_ENDIAN_H */ 52