Skip to content

Commit

Permalink
check endianness of floats
Browse files Browse the repository at this point in the history
  • Loading branch information
bjia56 authored Oct 17, 2024
1 parent a0fdd6c commit e7ec75f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
18 changes: 18 additions & 0 deletions cmake/CheckEndianness.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
include(TestBigEndian)

macro(define_python_endianness_macros)
TEST_BIG_ENDIAN(WORDS_BIGENDIAN)

# Test for float endianness
try_run(RESULT_VAR COMPILE_VAR
${CMAKE_BINARY_DIR}/check_float_endianness_result
${CMAKE_SOURCE_DIR}/cmake/check_float_endianness.c
)
if(RESULT_VAR EQUAL 1)
message(STATUS "System uses big-endian floating point format")
set(FLOAT_WORDS_BIGENDIAN 1)
else()
message(STATUS "System uses little-endian floating point format")
set(FLOAT_WORDS_BIGENDIAN 0)
endif()
endmacro()
4 changes: 2 additions & 2 deletions cmake/ConfigureChecks.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ include(CheckLibraryExists)
include(CheckSymbolExists)
include(CheckVariableExists)
include(cmake/PlatformTest.cmake)
include(TestBigEndian)
include(cmake/CheckEndianness.cmake)

message(STATUS "The system name is ${CMAKE_SYSTEM_NAME}")
message(STATUS "The system processor is ${CMAKE_SYSTEM_PROCESSOR}")
Expand Down Expand Up @@ -713,7 +713,7 @@ add_cond(CMAKE_REQUIRED_LIBRARIES HAVE_LIBINTL ${HAVE_LIBINTL})
add_cond(CMAKE_REQUIRED_LIBRARIES HAVE_LIBUTIL "${LIBUTIL_LIBRARIES}")
add_cond(CMAKE_EXTRA_INCLUDE_FILES HAVE_WCHAR_H wchar.h)

TEST_BIG_ENDIAN(WORDS_BIGENDIAN)
define_python_endianness_macros()

check_type_size(double SIZEOF_DOUBLE) # libffi and cpython
check_type_size(float SIZEOF_FLOAT)
Expand Down
18 changes: 18 additions & 0 deletions cmake/check_float_endianness.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include <stdio.h>

int main() {
// Test with a known float value (1.0f)
float test = 1.0f;
unsigned char *bytes = (unsigned char*)&test;

// The float 1.0f has a known IEEE-754 representation
// In big-endian, the first byte would be 0x3F
// In little-endian, the first byte would be 0x00
if (bytes[0] == 0x3F) {
// Big-endian float
return 1;
} else {
// Little-endian float
return 0;
}
}

0 comments on commit e7ec75f

Please sign in to comment.