active92
active92

Reputation: 654

Convert hex to corresponding bit

I have created a textfile to store some data retrieved from database.

This is my code.

CreateFile(String.Format("{0}\\U{1:X8}_C{2}_F{3}_B{4:X16}.TXT", 
                               userDir, 
                               staffWeaponEntity.StaffID.Oid, 
                               capsensepw, 
                               fingerprintID,
                               staffWeaponEntity.WeaponID.WeaponTypeID.Oid));

This is my output

".\\Data\\Tmp\\00000004\\USER\\U00000002_C000000_F00000000_B0000000000000004.TXT"

I would like to convert the last value which is 00000004 to bit pattern binary value which is 0000000000001000. How should I do it?

Upvotes: 1

Views: 98

Answers (1)

Rotem
Rotem

Reputation: 21917

You can use the overload of Convert.ToString which accepts a base (in this case base 2), and String.PadLeft to add the padding zeros.

CreateFile(String.Format("{0}\\U{1:X8}_C{2}_F{3}_B{4}.TXT", 
    userDir, 
    staffWeaponEntity.StaffID.Oid, 
    capsensepw, 
    fingerprintID,
    Convert.ToString(staffWeaponEntity.WeaponID.WeaponTypeID.Oid, 2).PadLeft(16, '0'));

Also, 4 in binary is 100, not 1000.


EDIT

It seems you just want the corresponding bit lit up. We can use bit shifting for this. Keep in mind the value you are using must be between 1 and 16.

CreateFile(String.Format("{0}\\U{1:X8}_C{2}_F{3}_B{4}.TXT", 
    userDir, 
    staffWeaponEntity.StaffID.Oid, 
    capsensepw, 
    fingerprintID,
    Convert.ToString(1 << (staffWeaponEntity.WeaponID.WeaponTypeID.Oid - 1), 2).PadLeft(16, '0'));

Upvotes: 1

Related Questions