rasn icon indicating copy to clipboard operation
rasn copied to clipboard

wromg byte order for Integer::to_unsigned_bytes_be

Open jsatchell opened this issue 6 months ago • 4 comments

If you do it on say 260 you get [1, 4, 0, 0, 0 , 0, 0, 0] , where I would expect [4, 1, 0, 0, 0, 0, 0, 0].

Found because SNMP agent stopped working when boot count exceeded 255!

jsatchell avatar Jul 12 '25 18:07 jsatchell

Thank you for your issue! I'm away on holidays currently but I can review a PR for a fix.

XAMPPRocky avatar Jul 12 '25 20:07 XAMPPRocky

I think the current functionality is correct?

260 as big-endian is [0b0000_0001, 0b0000_0100] (256 + 4). MSB in the lowest memory address.

Nicceboy avatar Jul 12 '25 22:07 Nicceboy

I think the right thing is 0, 0, 0, 0, 1, 4.

The zero padding should come first. If I convert to say u32, then do to_be_bytes on that, I get sensible answers.

On Sat, 12 Jul 2025, 23:56 Niklas Saari, @.***> wrote:

Nicceboy left a comment (librasn/rasn#483) https://github.com/librasn/rasn/issues/483#issuecomment-3066188033

I think the current functionality is correct?

260 as big-endian is [0b0000_0001, 0b0000_0100] (256 + 4). MSB in the lowest memory address.

— Reply to this email directly, view it on GitHub https://github.com/librasn/rasn/issues/483#issuecomment-3066188033, or unsubscribe https://github.com/notifications/unsubscribe-auth/AC4N6MAYKMG3QKMEKBH2QML3IGHA5AVCNFSM6AAAAACBMBCNTSVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTANRWGE4DQMBTGM . You are receiving this because you authored the thread.Message ID: @.***>

jsatchell avatar Jul 13 '25 05:07 jsatchell

The function currently works maybe a bit differently than one might expect. It is supposed to be used with the another tuple value which returns the amount of needed bytes to present the value.

E.g.

let value: u128 = 260;
let (bytes, needed) = value.to_unsigned_bytes_be();
dbg!(&bytes.as_ref()[..needed]);

&bytes.as_ref()[..needed] = [
    1,
    4,
]

In unsigned types leading zeros do not change the value, so for performance reasons they are first in the array. Otherwise there are many cases where we need to iterate complete byte array instead of the first bytes. The function was primarily created for internal codec usage.

Nicceboy avatar Jul 13 '25 09:07 Nicceboy