Using ghidra's python scripting engine, I'd like to create a struct which contains a big endian, unsigned integer. This field is always big endian, no matter what the endainess of the binary CPU is.

My first attempt:

def uint32b():
    dt = UnsignedIntegerDataType()
    for s in dt.getSettingsDefinitions():
        if isinstance(s, EndianSettingsDefinition):
            s.setBigEndian(dt.getDefaultSettings(), False)
    return dt

However, when the struct is applied to data, I'm still seeing a little-endian value. The field's "Default Settings -> Endian" still set to "Default".

default settings

1 Answer 1


The following script shows hows to create a structure and set its field to Big Endian byte order using the Ghidra Python API.

from ghidra.program.model.data import DataTypeConflictHandler
from ghidra.program.model.data import EndianSettingsDefinition
from ghidra.app.util.cparser.C import CParser

mystruct_txt = """
struct mystruct{
    uint32_t field1; 
    uint32_t field2;

# Get Data Type Manager
data_type_manager = currentProgram.getDataTypeManager()

# Create CParser
parser = CParser(data_type_manager)

# Parse structure
parsed_datatype = parser.parse(mystruct_txt)

# Add parsed type to data type manager
datatype = data_type_manager.addDataType(parsed_datatype, DataTypeConflictHandler.DEFAULT_HANDLER)

# Extract the first structure member i.e. mystruct.field1
field1 = datatype.components[0]

# Get Default Settings
field1_settings = field1.getDefaultSettings()

# Set endianess to big
field1_settings.setLong('endian', EndianSettingsDefinition.BIG)

If you have already created the structure earlier (using the editor or otherwise) you can omit the part where the structure is created and use getDataType to obtain it from the DataTypeManagerDB as shown below.

datatype = data_type_manager.getDataType("/mystruct")
field1 = datatype.components[0]
field1_settings = field1.getDefaultSettings()
field1_settings.setLong('endian', EndianSettingsDefinition.BIG)

After applying the structure to a piece data, you can right click on the field -> Data -> Default Settings and check that the default endianness is indeed Big Endian.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.