34

I think that this is not possible because Int32 has 1 bit sign and have 31 bit of numeric information and Int16 has 1 bit sign and 15 bit of numeric information and this leads to having 2 bit signs and 30 bits of information.

If this is true then I cannot have one Int32 into two Int16. Is this true?

Thanks in advance.

EXTRA INFORMATION: Using Vb.Net but I think that I can translate without problems a C# answer.

What initially I wanted to do was to convert one UInt32 to two UInt16 as this is for a library that interacts with WORD based machines. Then I realized that Uint is not CLS compliant and tried to do the same with Int32 and Int16.

EVEN WORSE: Doing a = CType(c And &HFFFF, Int16); throws OverflowException. I expected that statement being the same as a = (Int16)(c & 0xffff); (which does not throw an exception).

jason
  • 236,483
  • 35
  • 423
  • 525
Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207

13 Answers13

40

This can certainly be done with no loss of information. In both cases you end up with 32 bits of information. Whether they're used for sign bits or not is irrelevant:

int original = ...;

short firstHalf = (short) (original >> 16);
short secondHalf = (short) (original & 0xffff);

int reconstituted = (firstHalf << 16) | (secondHalf & 0xffff);

Here, reconstituted will always equal original, hence no information is lost.

Now the meaning of the signs of the two shorts is a different matter - firstHalf will be negative iff original is negative, but secondHalf will be negative if bit 15 (counting 0-31) of original is set, which isn't particularly meaningful in the original form.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • If you don't use a mask in the first case, why use the mask for the second case? Is it that a cast in c# actually tests if there is info in the first part? Or does it chop it off like an and would? – Toad Dec 09 '09 at 11:59
  • 1
    As I have explained in reinier's answer, you cannot assume little endiannes in .NET. – Tamas Czinege Dec 09 '09 at 12:00
  • 2
    @DrJokepu: You *can* assume what shifting and masking will do, however it's stored in memory. A right-shift will be sign-extended, but the cast to `short` will effectively mask it. – Jon Skeet Dec 09 '09 at 12:08
  • @Jon Skeet: For simple splitting and reconstitution this is not an issue, however if they have different meanings (e.g. bits 0..15 is an X coordinate and bits 16..31 is a Y coordinate) you will end up mixing up the two. I have no XBOX 360 nor an emulator so I can't test it but it seems to me that this is what would happen. – Tamas Czinege Dec 09 '09 at 12:17
  • I just tested your solution with 0x7FFFFFFF as original, and original = 2147483647 and reconstructed = -1 so something is wrong here. – Ignacio Soler Garcia Dec 09 '09 at 12:22
  • @DrJokepu, It's about storing, not about meaning after storing. It's a formal issue, not a semantic one. I my view the requirements are met if you can reconstitute it with the same meaning after splitting – Peter Dec 09 '09 at 12:23
  • @Somos: Fixed, thanks. I'd forgotten about sign extension on short to int promotion. @DrJokepu: I believe you're wrong, simply because endianness is about the storage, not the *logical* bit representation. – Jon Skeet Dec 09 '09 at 12:54
  • isn't this bugged since firstHalf << 16 will always be zero since it will be performed on a short and not on an int? I think that you will have to cast them to int first. – Etan Dec 09 '09 at 12:57
  • 4
    It implicitly converts it to int, before the shifting. – treaschf Dec 09 '09 at 13:04
  • Ok, now the problem is that this construction does not work with Vb.Net as I explain on an edit of the question but this will be a new Question. Thanks. – Ignacio Soler Garcia Dec 09 '09 at 14:01
  • @Roman Boiko: Given your answer, that's a very strange result IMO. I think I'll leave this answer as it is, as for most other people with a similar problem it may well be a better solution :) – Jon Skeet Dec 09 '09 at 16:36
  • In fact, now I think that your behavior is more intuitive than the one which I suggested. :) – Roman Boiko Dec 09 '09 at 18:28
16

This should work:

int original = ...;
byte[] bytes = BitConverter.GetBytes(original);
short firstHalf = BitConverter.ToInt16(bytes, 0);
short secondHalf = BitConverter.ToInt16(bytes, 2);

EDIT:

tested with 0x7FFFFFFF, it works

byte[] recbytes = new byte[4];
recbytes[0] = BitConverter.GetBytes(firstHalf)[0];
recbytes[1] = BitConverter.GetBytes(firstHalf)[1];
recbytes[2] = BitConverter.GetBytes(secondHalf)[0];
recbytes[3] = BitConverter.GetBytes(secondHalf)[1];
int reconstituted = BitConverter.ToInt32(recbytes, 0);
Agg
  • 445
  • 3
  • 9
  • I didn't read your solution because I already picked one. But I will use yours. Thanks. – Ignacio Soler Garcia Dec 14 '09 at 08:45
  • When using `BitConverter` always adapt your code to `BitConverter.IsLittleEndian` otherwise it might break when you port it over to a different platform. – Peter Feb 24 '15 at 09:02
7

Jon's answer, translated into Visual Basic, and without overflow:

Module Module1
    Function MakeSigned(ByVal x As UInt16) As Int16
        Dim juniorBits As Int16 = CType(x And &H7FFF, Int16)
        If x > Int16.MaxValue Then
            Return juniorBits + Int16.MinValue
        End If
        Return juniorBits
    End Function

    Sub Main()
        Dim original As Int32 = &H7FFFFFFF    
        Dim firstHalfUnsigned As UInt16 = CType(original >> 16, UInt16)
        Dim secondHalfUnsigned As UInt16 = CType(original And &HFFFF, UInt16)
        Dim firstHalfSigned As Int16 = MakeSigned(firstHalfUnsigned)
        Dim secondHalfSigned As Int16 = MakeSigned(secondHalfUnsigned)

        Console.WriteLine(firstHalfUnsigned)
        Console.WriteLine(secondHalfUnsigned)
        Console.WriteLine(firstHalfSigned)
        Console.WriteLine(secondHalfSigned)
    End Sub
End Module

Results:

32767
65535
32767
-1

In .NET CType(&Hffff, Int16) causes overflow, and (short)0xffff gives -1 (without overflow). It is because by default C# compiler uses unchecked operations and VB.NET checked.

Personally I like Agg's answer, because my code is more complicated, and Jon's would cause an overflow exception in checked environment.

I also created another answer, based on code of BitConverter class, optimized for this particular task. However, it uses unsafe code.

Community
  • 1
  • 1
Roman Boiko
  • 3,576
  • 1
  • 25
  • 41
4

yes it can be done using masking and bitshifts

 Int16 a,b;
 Int32 c;

 a = (Int16) (c&0xffff);
 b = (Int16) ((c>>16)&0xffff);

EDIT

to answer the comment. Reconstructionworks fine:

 Int16 a, b;
 Int32 c = -1;

 a = (Int16)(c & 0xffff);
 b = (Int16)((c >> 16) & 0xffff);

 Int32 reconst = (((Int32)a)&0xffff) | ((Int32)b << 16);

 Console.WriteLine("reconst = " + reconst);

Tested it and it prints -1 as expected.

EDIT2: changed the reconstruction. The promotion of the Int16 to Int32 caused all sign bits to extend. Forgot that, it had to be AND'ed.

Toad
  • 15,593
  • 16
  • 82
  • 128
  • 1
    The .NET VM is not necessarily little endian. The XBOX 360 runs on the PowerPC architecture and is configured to use big endian. The XNA framework is a version of the .NET Framework by Microsoft for developing games and applications for the XBOX 360. So you can't assume little endiannes. – Tamas Czinege Dec 09 '09 at 11:58
  • 4
    I'm not assuming anything. I just chop it into 2 pieces like asked – Toad Dec 09 '09 at 12:00
  • 1
    reinier: Fair enough. I'm only saying it because if the first and second half have different meanings, you might want to make sure that you get the right half. – Tamas Czinege Dec 09 '09 at 12:05
  • 3
    @DrJokepu: I don't believe endianness will affect this at all. The result of shifting is well-defined in terms of the *logical* bits of the integer, regardless of in-memory representation. If you believe there's some observable difference, please provide a sample. – Jon Skeet Dec 09 '09 at 12:10
  • I just tested your solution like the one by @Jon and it is not converting fine the value 0x7fffffff, when reconstructed again it fails. – Ignacio Soler Garcia Dec 09 '09 at 12:31
  • Hi, I tested it too (see my EDIT) and it works fine for the -1 case – Toad Dec 09 '09 at 12:49
  • But not for the 0x7FFFFFFF value, just try it. – Ignacio Soler Garcia Dec 09 '09 at 13:23
  • 1
    @somos: good call. I changed the reconstruction code. The problem was that a Negative Int16 gets it's sign bit extended to the full32 bits. Which we don't want so I had to AND it., – Toad Dec 09 '09 at 13:30
  • @reinier: Yes, that was what was wrong with mine too. There's no need to explicitly cast to an int though - that's implicit in the shift. – Jon Skeet Dec 09 '09 at 13:31
  • Ok, now the problem is that this construction does not work with Vb.Net as I explain on an edit of the question but this will be a new Question. Thanks. – Ignacio Soler Garcia Dec 09 '09 at 14:00
3

Why not? Lets reduce the number of bits for the sake of simplicity : let's say we have 8 bits of which the left bit is a minus bit.

[1001 0110] // representing -22

You can store it in 2 times 4 bits

[1001] [0110] // representing   -1 and 6

I don't see why it wouldn't be possible, you twice have 8 bits info

EDIT : For the sake of simplicity, I didn't just reduce the bits, but also don't use 2-complementmethod. In my examples, the left bit denotes minus, the rest is to be interpreted as a normal positive binary number

Peter
  • 47,963
  • 46
  • 132
  • 181
  • This certainly seems closer to the original intent of the question. – Kenan E. K. Dec 09 '09 at 12:08
  • @Peter: A small nitpick... In 8-bit two's complement `10010110` represents `-106`, and `-22` would actually be represented by `11101010`. Similarly, in 4-bit two's complement `1001` represents `-15`, and `-1` would actually be represented by `1111`. – LukeH Dec 09 '09 at 13:29
  • @Luke : it's clearly not two complement :-) , no it's just pseudocode for illustration – Peter Dec 09 '09 at 13:32
  • @Peter: Could be confusing for the OP and/or future readers though, if they can't figure out why `10010110` doesn't work out as `-22` in their calculations etc. – LukeH Dec 09 '09 at 13:42
  • (Oops, a mistake in my first comment: `1001` represents `-7` and *not* `-15`.) – LukeH Dec 09 '09 at 13:46
  • @Luke : they won't run into integers represented by 4 bits and 8 bits any time soon, but since you are right I edited my question with the explanation. – Peter Dec 09 '09 at 15:27
  • @Peter: if you use the left bit to denote minus, and the rest as normal number, you have **two** representations of 0: 00000000 and 10000000. And no representations of -32768. Thus **loss of information**. I also had this problem. – Roman Boiko Dec 11 '09 at 08:27
  • @Roman : imho you are mingling things, I know what you mean : but still you can transform the 8 bits to 2 x 4 bits without loss of info. In the first example 00000000 and 10000000 indeed both mean zero, but that has nothing to do with the fact that it can be split up. – Peter Dec 11 '09 at 08:42
2

You can use StructLayout in VB.NET:

correction: word is 16bit, dword is 32bit

<StructLayout(LayoutKind.Explicit, Size:=4)> _
   Public Structure UDWord
      <FieldOffset(0)> Public Value As UInt32
      <FieldOffset(0)> Public High As UInt16
      <FieldOffset(2)> Public Low As UInt16

      Public Sub New(ByVal value As UInt32)
         Me.Value = value
      End Sub

      Public Sub New(ByVal high as UInt16, ByVal low as UInt16)
         Me.High = high
         Me.Low = low
      End Sub
   End Structure

Signed would be the same just using those types instead

<StructLayout(LayoutKind.Explicit, Size:=4)> _
   Public Structure DWord
      <FieldOffset(0)> Public Value As Int32
      <FieldOffset(0)> Public High As Int16
      <FieldOffset(2)> Public Low As Int16

      Public Sub New(ByVal value As Int32)
         Me.Value = value
      End Sub

      Public Sub New(ByVal high as Int16, ByVal low as Int16)
         Me.High = high
         Me.Low = low
      End Sub
   End Structure

EDIT:

I've kind of rushed the few times I've posted/edited my anwser, and yet to explain this solution, so I feel I have not completed my answer. So I'm going to do so now:

Using the StructLayout as explicit onto a structure requires you to provide the positioning of each field (by byte offset) [StructLayoutAttribute] with the FieldOffset attribute [FieldOffsetAttribute]

With these two attributes in use you can create overlapping fields, aka unions.

The first field (DWord.Value) would be the 32bit integer, with an offset of 0 (zero). To split this 32bit integer you would have two additional fields starting again at the offset of 0 (zero) then the second field 2 more bytes off, because a 16bit (short) integer is 2 bytes a-peice.

From what I recall, usually when you split an integer they normally call the first half "high" then the second half "low"; thus naming my two other fields.

With using a structure like this, you could then create overloads for operators and type widing/narrowing, to easily exchange from say an Int32 type to this DWord structure, aswell as comparasions Operator Overloading in VB.NET

DanStory
  • 371
  • 2
  • 6
2

Unsafe code in C#, overflow doesn't occur, detects endianness automatically:

using System;
class Program
{
    static void Main(String[] args)
    {
        checked // Yes, it works without overflow!
        {
            Int32 original = Int32.MaxValue;
            Int16[] result = GetShorts(original);
            Console.WriteLine("Original int: {0:x}", original);
            Console.WriteLine("Senior Int16: {0:x}", result[1]);
            Console.WriteLine("Junior Int16: {0:x}", result[0]);
            Console.ReadKey();
        }
    }
    static unsafe Int16[] GetShorts(Int32 value)
    {
        byte[] buffer = new byte[4];
        fixed (byte* numRef = buffer)
        {
            *((Int32*)numRef) = value;
            if (BitConverter.IsLittleEndian)
                return new Int16[] { *((Int16*)numRef), *((Int16*)numRef + 1) };
            return new Int16[] { 
                (Int16)((numRef[0] << 8) | numRef[1]),  
                (Int16)((numRef[2] << 8) | numRef[3])
            };
        }
    }
}
Roman Boiko
  • 3,576
  • 1
  • 25
  • 41
2

You can use StructLayout to do this:

[StructLayout(LayoutKind.Explicit)]
        struct Helper
        {
            [FieldOffset(0)]
            public int Value;
            [FieldOffset(0)]
            public short Low;
            [FieldOffset(2)]
            public short High;
        }

Using this, you can get the full Value as int , and low part, hight part as short.

something like:

var helper = new Helper {value = 12345};
Green Su
  • 2,318
  • 2
  • 22
  • 16
0

Due to storage width (32bits and 16bits), converting Int32 to Int16 may imply a loss of information, if your Int32 is greater than 32767.

Laurent Etiemble
  • 27,111
  • 5
  • 56
  • 81
0

If you look at the bit representation, then you are correct.

You can do this with unsigned ints though, as they don't have the sign bit.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

Int32 num = 70000;

        string str = Convert.ToString(num, 2);
    //convert INT32 to Binary string   
        Int32 strl = str.Length;
    //detect string length


        string strhi, strlo;
    //ifvalue is greater than 16 bit 
        if (strl > 16)
        {
           int lg = strl - 16;
          //dtect bits in higher word 
           strlo = str.Substring(lg, 16);
     ///move lower word string to strlo 

            strhi = str.Substring(0, lg);
   //mov higher word string to strhi

        }
        else
//if value is less than 16 bit
        {
           strhi = "0";
//set higher word zero
           strlo = str;
///move lower word string to strlo 

        }

        Int16 lowword, hiword;
        lowword = Convert.ToInt16(strlo, 2);
        hiword = Convert.ToInt16(strhi, 2);
        ////convert binary string to int16
        }
Sumit
  • 1
  • 1
0

I did not use bitwise operators but for unsigned values, this may work:

public (ushort, ushort) SplitToUnsignedShorts(uint value)
{
    ushort v1 = (ushort) (value / 0x10000);
    ushort v2 = (ushort) (value % 0x10000);

    return (v1, v2);
}

Or an expression body version of it:

public (ushort, ushort) SplitToUShorts(uint value)
    => ((ushort)(value / 0x10000), (ushort)(value % 0x10000));

As for signs, you have to decide how you want to split the data. There can only be 1 negative output out of two. Remember a signed value always sacrifices one bit to store the negative state of the number. And that essentially 'halves' the maximum value you can have in that variable. This is also why uint can store twice as much as a signed int.

As for encoding it to your target format, you can either choose make the second number an unsigned short, to preserve the numerical value, or you can manually encode it such that the one bit now represent the sign of that value. This way although you will lose the originally intended numeric value for a sign bit, you don't lose the original binary data and you can always reconstruct it to the original value.

In the end it comes down to how you want to store and process that data. You don't lose the bits, and by extension, the data, as long as you know how to extract the data from (or merge to) your encoded values.

Glitch
  • 595
  • 6
  • 18
0

you can use this Nuget package LSharpCode.XExtensions When you had installed it ,you can use it in this way:

using LSharpCode.XExtensions.MathExtensions;
Int32 varInt32name;
Int16 varint16nameLow;
Int16 varint16nameHigh;
varInt32name.ToTwoInt16(out varint16nameLow,out varint16nameHigh);
luka
  • 605
  • 8
  • 15