Reputation: 173
I ran into a dead-end for what I think should be a simple solution. Basically, I have:
List<Uint16> header = new List<UInt16>();
Then I populate it with data but later I need to join a couple of elements into Int32 and I have no idea what is the best way to do it. Are there any .NET calls I can make to join these two into Uint32?
Thanks
Upvotes: 0
Views: 4194
Reputation: 1
Function get_DWord(ByVal D1 As Short, ByVal D2 As Short) As Integer
Dim Bits As String = Convert.ToString(D1, 16)
Dim length As Integer = Bits.Length
If length < 4 Then
For I As Integer = 0 To 4 - length
Bits = "0" & Bits
Next
End If
Dim Bits2 As String = Convert.ToString(D2, 16)
Dim No As Integer = Convert.ToInt32(Bits2 & Bits, 2)
Return No
End Function
Upvotes: 0
Reputation: 61950
I think we also need to take care of the endianness of the system.
Stored value: 0x00000001 In memory representation: Memory Address Low High 0 1 2 3 +------+------+------+------+ | 00 | 00 | 00 | 01 | Big Endian Representation +------+------+------+------+ stores the least significant byte in higher memory address. So we get 0 in lower address. Low High 0 1 2 3 +------+------+------+------+ | 01 | 00 | 00 | 00 | Little Endian Representation +------+------+------+------+ stores the least significant byte in lower memory address.
Therefore if we need to paste two uint16
then first we need to understand the byte ordering.
uint16 val1, val2; val1 +------+------+ +------+------+ | b1 | b2 | OR | b2 | b1 | +------+------+ +------+------+ (paste) (paste) val2 +------+------+ +------+------+ | b3 | b4 | OR | b4 | b3 | +------+------+ +------+------+ ===============================+=============================== paste(val1,val2) | paste(val2,val1) 0 1 2 3 | 0 1 2 3 +------+------+------+------+ | +------+------+------+------+ | b1 | b2 | b3 | b4 | | | b4 | b3 | b2 | b1 | +------+------+------+------+ | +------+------+------+------+ val1 val2 | val2 val1 LITTLE Endian BIG Endian
Therefore the byte ordering needs to be considered.
To check if the Endinness of the system you can use
endian = (((char *)&x)[0]) ? 0 : 1;
Where 0
is Little and 1
is Big. (I am not explaining this here).
Depending on this output you can use the paste
function to get the uint16
s pasted.
For completeness sake I am writing the paste function.
uint32 paste (uint16 n1, uint16 n2)
{
return ((uint32) n1 << 16)| (uint) n2;
}
Upvotes: 1
Reputation: 490
If by join them you mean use one Uint16 as the lowest 16 bits of a 32 bit Uint and the other as the highest 16 bits then you can use bit-wise arithmetic and shifting. Something like:
Uint16 u1;
Uint16 u2;
Uint32 = (Uint32)u1 << 16 | (Uint32)u2;
Upvotes: 0
Reputation:
You can use Bitwise Operators:
uint num = (uint)((header.ElementAt(0) << 16) | header.ElementAt(1));
Upvotes: 2
Reputation: 19526
You can use bit shifting to do it:
var num = (uint)((header.ElementAt(0) << 16) | header.ElementAt(1));
That's assuming the element at 0 is most significant.
Upvotes: 7