Skip to content

Apparently incorrect value from [Convert]::ToString() . When given an SByte which is negative, a value representing a sign extended 16 bits is returned #1

@AltitudeApps

Description

@AltitudeApps

I think that this is actually an issue with the .NET runtime, not PowerShell, but I can't figure out exactly where in System.Private.CoreLib/src/System/Convert.cs to look for the code which is responsible for this.

However, I did find this issue which mentions the behavior:
#dotnet/runtime#24910 (Add Convert.ToString(sbyte value, int toBase) And Allow _ separator)

When I use:
sbyte n = -1;
var x = Convert.ToString(n, 2);
Console.WriteLine(x);

the output is "1111111111111111" because the ToString casts n to short!

Prerequisites

Steps to reproduce

When passing a negative SByte value to [convert]::ToString(), a string representing 16 bits is returned, instead of one representing 8 bits.

Expected behavior

PS> $bb = 0b1y; ($bb = $bb -shl 7); $bb.GetType().Name; [Convert]::ToString( $bb, 2 );
-128
SByte
10000000

Actual behavior

PS> $bb = 0b1y; ($bb = $bb -shl 7); $bb.GetType().Name; [Convert]::ToString( $bb, 2 );
-128
SByte
1111111110000000

Error details

There isn't any error message, but I regard the output with suspicion and doubt.

Environment data

PS C:\Program Files\PowerShell\7.5.0-rc.1> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.5.0-rc.1
PSEdition                      Core
GitCommitId                    7.5.0-rc.1
OS                             Microsoft Windows 10.0.19045
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Backstory

I was struggling to understand the weird behavior I was seeing when dealing with bit shifting operations, which turned out to be the selective sign extension discussed in issue #PowerShell#19218

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions