Skip to content

Mixed Signed and Unsigned Integers in Arithmetic Operations in GO #1

@etheleon

Description

@etheleon

Introduction

In the generated Go code from the Kaitai Struct (.ksy) definition, there is an arithmetic operation that mixes signed (int8) and unsigned (uint8) integers. Go does not allow such operations without explicit type conversion, resulting in a compilation error:

invalid operation: (this.Value1 + (this.Value2 << 8)) + (this.Value3 << 16) (mismatched types uint8 and int8)

.ksy definition

The .ksy definition of value is as follows:

  value:
    seq:
      - id: value1
        type: u1
      - id: value2
        type: u1
      - id: value3
        type: s1
    instances:
      calc_value:
        value: value1 + (value2 << 8) + (value3 << 16)

Generated Go Code

}
func (this *OpenapiMessage_Value) CalcValue() (v int, err error) {
	if this._f_calcValue {
		return this.calcValue, nil
	}
	this.calcValue = int(((this.Value1 + (this.Value2 << 8)) + (this.Value3 << 16)))
	this._f_calcValue = true
	return this.calcValue, nil
}

Proposed Fix

func (this *OpenapiMessage_Value) CalcValue() (v int, err error) {
    if this._f_calcValue {
        return this.calcValue, nil
    }

    // Convert values to appropriate types and perform arithmetic
    this.calcValue = int(
        int32(this.Value1) +          // value1 (u1 -> uint32)
        (int32(this.Value2) << 8) +  // value2 (u1 -> uint32, shifted left by 8 bits)
        (int32(this.Value3) << 16),   // value3 (s1 -> int32, shifted left by 16 bits)
    )

    this._f_calcValue = true
    return this.calcValue, nil
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions