195dbdf32Schristos /* 295dbdf32Schristos * Copyright (c) 2020 Yubico AB. All rights reserved. 395dbdf32Schristos * Use of this source code is governed by a BSD-style 495dbdf32Schristos * license that can be found in the LICENSE file. 5*2d40c451Schristos * SPDX-License-Identifier: BSD-2-Clause 695dbdf32Schristos */ 795dbdf32Schristos 895dbdf32Schristos #include "openbsd-compat.h" 995dbdf32Schristos 1095dbdf32Schristos #if defined(_WIN32) && !defined(HAVE_ENDIAN_H) 1195dbdf32Schristos 1295dbdf32Schristos /* 1395dbdf32Schristos * Hopefully, if the endianness differs from the end result, the compiler 1495dbdf32Schristos * optimizes these functions with some type of bswap instruction. Or, 1595dbdf32Schristos * otherwise, to just return the input value unmodified. GCC and clang 1695dbdf32Schristos * both does these optimization at least. This should be preferred over 1795dbdf32Schristos * relying on some BYTE_ORDER macro, which may or may not be defined. 1895dbdf32Schristos */ 1995dbdf32Schristos 2095dbdf32Schristos uint32_t htole32(uint32_t in)2195dbdf32Schristoshtole32(uint32_t in) 2295dbdf32Schristos { 2395dbdf32Schristos uint32_t out = 0; 2495dbdf32Schristos uint8_t *b = (uint8_t *)&out; 2595dbdf32Schristos 2695dbdf32Schristos b[0] = (uint8_t)((in >> 0) & 0xff); 2795dbdf32Schristos b[1] = (uint8_t)((in >> 8) & 0xff); 2895dbdf32Schristos b[2] = (uint8_t)((in >> 16) & 0xff); 2995dbdf32Schristos b[3] = (uint8_t)((in >> 24) & 0xff); 3095dbdf32Schristos 3195dbdf32Schristos return (out); 3295dbdf32Schristos } 3395dbdf32Schristos 3495dbdf32Schristos uint64_t htole64(uint64_t in)3595dbdf32Schristoshtole64(uint64_t in) 3695dbdf32Schristos { 3795dbdf32Schristos uint64_t out = 0; 3895dbdf32Schristos uint8_t *b = (uint8_t *)&out; 3995dbdf32Schristos 4095dbdf32Schristos b[0] = (uint8_t)((in >> 0) & 0xff); 4195dbdf32Schristos b[1] = (uint8_t)((in >> 8) & 0xff); 4295dbdf32Schristos b[2] = (uint8_t)((in >> 16) & 0xff); 4395dbdf32Schristos b[3] = (uint8_t)((in >> 24) & 0xff); 4495dbdf32Schristos b[4] = (uint8_t)((in >> 32) & 0xff); 4595dbdf32Schristos b[5] = (uint8_t)((in >> 40) & 0xff); 4695dbdf32Schristos b[6] = (uint8_t)((in >> 48) & 0xff); 4795dbdf32Schristos b[7] = (uint8_t)((in >> 56) & 0xff); 4895dbdf32Schristos 4995dbdf32Schristos return (out); 5095dbdf32Schristos } 5195dbdf32Schristos 5295dbdf32Schristos #endif /* WIN32 && !HAVE_ENDIAN_H */ 53