简体   繁体   中英

long/int to UINT64 conversion and back to long on C# - when can I lose data?

I have C++ server which sends me data to C# client. The server reads some values from database. It has parser used for serializing data to be sent over network which can only send unsigned numbers - eg uint64 .

But in the database I believe one value it sends me has type int/long . So after reading from database probably it casts it to uint64 .

On the C# side I do following with that number

balance = unchecked((long)answer.Find(ModuleGlobals.TAG_TI_BALANCE).Get_QWORD());

where balance is of type long . But Get_QWORD on C# returns ulong - as I said parser only works with unsigned numbers.

So in what situations can I lose data above? Or I will always end up with the data that server sent me? (even in case of negative integers?)


Basically the flow is like this I guess

int/long --> converted/cast to uint64 by server --> Send over network --> Parsed as ulong --> Cast to long (as I showed in my code)

Needs revision as question changed.


Change it to

balance = unchecked((int)answer.Find(ModuleGlobals.TAG_TI_BALANCE).Get_QWORD());`

C# 's long is set at 64-bit. C++ 's long varies. If both are same size (and same representation) everything is fine.

But on Windows, C++'s long is 32-bit. So, you are going to lose the sign-bit on negative numbers. For example sending -1 from the C++ front will give you a 0xFFFFffff in C#. To get 0xFFFFffff back to -1 again, you have to cast it to a same size type, which is int .

But as you see this still assumes a certain size of long in your C++ code (which is Ok if you only target Windows). If you have access to the C++ code, better change long to a fixed size type like uint64_t from <cstdint> and cast it to long on the C# side as you were doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM