C# - Multiple Errors - c#

After writing my second program in C#, I receive an error:
Error in Compiler
The error might pertain to the library
or it might be on the Conversion
or the namespace
using System;
namespace MagpantayUserInfoProg {
class UserInfo {
static void Main() {
string name, gender; // Variables for storing words
int contact, age; // Variables for storing integers
Console.Write("Name: "); // Let the user input his name
name = Console.ReadLine(); // System reads data
Console.Write("Gender: "); // Let the user input his gender
gender = Console.ReadLine();// System reads data
Console.Write("Age: "); // Let the user input his age
age = Int32.Parse(Console.ReadLine()); // System reads data
Console.Write("Mobile Number: "); // Let the user input his contact number
contact = Int32.Parse(Console.ReadLine()); // System reads data
// Display Output
Console.Write("Name: {0}\n", name);
Console.Write("Gender: {0}\n", gender);
Console.Write("Age: {0}\n", age);
Console.Write("Mobile Number: {0}\n", contact);
Console.ReadLine();
}
}
}

mobile number too large for int
https://learn.microsoft.com/tr-tr/dotnet/csharp/language-reference/builtin-types/integral-numeric-types
check int range
also use string for storing mobile number

Let's dissect the error message:
Value was either too large or too small for an Int32
So, that tells us the problem is somewhere where we're creating an Int32, and Int32.Parse(Console.ReadLine()); fits the bill, not only are we creating an Int32 here, but this is also the point in the program where the error (exception) is encountered (thrown). But why? Well, because computers don't have infinite memory, so a while ago people (read: software developers) decided on a bunch of standards on how to represent data inside a computer, and those standards contain limits, and the limit for an Int32 (which by the way is the standard int in C#) is no smaller than -2,147,483,648 and no larger than 2,147,483,647 (source), but your phone number is 09,563,977,528, larger than the maximum allowed, and hence the error.
So what do we do now? Well, we could use a larger integral type, like long and Convert.ToInt64, but that's just a band aid solution, instead we should use a string (or a more specialized data structure*). Think about it, is a phone number really just a number? No, it isn't, for one the phone numbers 09563977528 and 9563977528 aren't the same right? But if they're were regular old numbers, they would be, 02 and 2 are the exact same number. Additionally, it doesn't really make sense to use arithmetic operations on phone numbers, there's never a need to multiply or subtract or add or whatever 2 phone numbers together. So for those reasons, I'd suggest we just leave phone numbers as strings.
* A good exercise for when you learn about classes and structs would be to implement a custom class representing a phone number

As others have pointed out, the number is too large to be stored as an Int (Int32) value which can handle any number between
-2,147,483,648 and 2,147,483,647
Generally, you should not store a phone number as a numeric value anyway, because many phone numbers include a leading zero which is critical but cannot be stored if you store the value as a number. But as not all phone numbers do include a leading zero, then you can't assume that there always is one.
So then you need to store this as a string value instead, and then include some validation to ensure that only numbers are entered.
There are many different ways to do this, so you can investigate further to see which suits you, but as an example you can try this, which will scan the string to check that each character is a digit.
Console.Write("Mobile Number: "); // Let the user input his contact number
contact = Console.ReadLine(); // System reads data
if (contact.All(char.IsDigit))
{
// String only contains numbers
}
else
{
//Handle error here
}
Edit:
Of course this solution only allows digit. So if the user wishes to prefix a country code using a '+', then this will not be supported. So then you need to change the solution to support this.
Also, FYI: You don't have a compiler error, you have a runtime exception.

Related

Make a method that checks if the user input is equal to a random number [duplicate]

This question already has answers here:
random number guessing game
(8 answers)
Random Number Guessing Game C#
(3 answers)
C# Guess random number
(2 answers)
Closed 4 years ago.
I have this exercise:
Make a method that generates a random number between 1 and 100.
Ask the user to guess a number between 1 and 100.
Make a method that checks if the user's guess is equal to the random number that has been generated. This method will also say "higher" or "lower" until the user guesses the random number.
I have no problem with steps 1 and 2, but I'm having problems with the 3rd step. Here is my code so far:
static void Main(string[] args)
{
int randomNumber = GenerateRandomNumberMethod();
Console.WriteLine("Guess a number between 1 and 100:");
}
// generate random number method (step 2)
public static int GenerateRandomNumberMethod()
{
Random rdn = new Random();
int random = rd.Next(1,100);
return random;
}
//step 3 (Method to compare guessed number with random number)?
I hope it is not a stupid question, the answer is probably pretty simple.
Well, the first thing you want to do is to store the generated random number in a variable, so that it will not be re-generated after each time the user attempts.
The second thing you want to do is to create a method that will compare the user input against the randomly-generated number, and return a value indicating if the user input is smaller, equal, or higher than the generated number (A bool? might be a good choice for this).
The third thing you need is a safe way to convert the string the user entered to an int.
Do not make the common mistake of using Convert.ToInt32 - use int.TryParse instead. You do not want to throw an exception if the user entered Zohar instead of 123.
The fourth thing to do is to implement a loop - that will keep getting inputs from the user and tell them if the number is too high or too low. Exit the loop if the number is the same as the generated random number.
The last thing to do is to tell the user they finally guessed the correct number and exit (or maybe restart) the game.
Since it's clearly a homework assignment, I'll leave the coding part for you to handle, because you will not learn anything if you don't at least do it yourself, but at least now you have a plan.
Try
int userGuess = int.Parse(Console.ReadLine());
See this previous question on reading user input.
See this previous question on your exact problem.
See comments for note on int.Parse()

RFID - Leading zero issue

I'm developing a Xamarin.iOS application using the LineaPro 5 peripheral, which is able to scan barcodes, RFID cards and swipe magnetic cards. I have the basic RFID functionality working, and the data coming from the Linea that I care about is the UID of the card (a byte array).
In our application, which interacts with a web server, the format in which we use to identify these cards is decimal, thus I have this code which translates the UID byte array to the decimal string we need:
// Handler attached to the RFID Scan event invoked by the LineaPro
void HandleRFIDScanned (DTDeviceDelegate Dispatcher, RFIDScannedEventArgs Arguments)
{
if ( Arguments == null || Arguments.Data == null || Arguments.Data.UID == null )
InvalidRFIDScanned ();
else
{
byte[] SerialArray = new byte[Arguments.Data.UID.Length];
System.Runtime.InteropServices.Marshal.Copy(Arguments.Data.UID.Bytes, SerialArray, 0, SerialArray.Length);
string Hex = Util.ByteArrayToHexString (SerialArray);
if ( string.IsNullOrWhiteSpace (Hex) )
InvalidRFIDScanned ();
else
{
string DecimalSerial = ulong.Parse (Hex, System.Globalization.NumberStyles.HexNumber).ToString ();
ValidRFIDScanned (DecimalSerial);
}
}
//Disconnecting card so another can be scanned
NSError RFDisconnectError;
LineaPRO.Shared.Device.RfRemoveCard (Arguments.CardIndex, out RFDisconnectError);
}
//Byte array to hexadecimal string conversion
public static string ByteArrayToHexString (byte[] Bytes)
{
StringBuilder hex = new StringBuilder();
foreach (byte b in Bytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
However, I have discovered a very concerning issue with some of the RFID cards we have been issued. We have a variety of cards, differing in style and ISO standard, that the mobile app needs to scan. One of which (I believe of the Mifare Classic standard, though I cannot confirm at this moment) is always a ten-digit number from this particular RFID card provider, though some of them begin with the number 0, as in this picture:
This causes a huge issue with my byte array conversion, as the hexadecimal string is parsed into an unsigned long type, and the leading zero is dropped. We use another set of USB RFID readers in a separate application in order to store these RFID card ID's into a database, though somehow those USB readers are able to pick up the leading zero.
Therefore, a conflict is reached when using the mobile application, in which the UID's leading zero is dropped, since the data passed to the API is checked against the database and is then not considered a match, because of the missing zero.
I have looked at all of the data received by the LineaPro in my event handler and that byte array is the only thing which holds the UID of the card, so as long as we are using the decimal representation of the UIDs, there is no way for the mobile app to determine whether or not a zero should be there, unless:
Perhaps some of the RFID standards have a specific restriction on the number of digits in the UID's decimal representation? For example, if this type of card always has an even or specific number of decimal digits, I can pad the string with an extra zero if necessary.
The LineaPro is simply not delivering sufficient data, in which case I'm probably screwed.
You don't have enough information to solve your problem. If the ID numbers are always supposed to be 10 digits it is trivial to use a format string to add leading zeros as needed.
I'd say try always padding the UID to 10 digits with leading zeros and then run a large number of test values through it.
As you say, if your device is dropping valid data from the beginning of the ID then you are screwed.
I've discovered that the specific configuration settings used with our USB RFID readers, in conjunction with the format of cards received from the vendor, are to blame. Here is a screenshot of the configuration we use with the USB readers:
We have them set to force a 10 digit-long decimal UID when reading, padding shorter IDs and truncating longer ones. I have informed the other developers that the proper method of reading these IDs should be in their proper hexadecimal format with no specific length, so as to support other RFID card types without any hard-coded ID formats.

Generate a unique PIN code based on the phone number

With a unique phone number like 0241194000, I want to generate a PIN code based on the phone number and also a way to check or validate that the PIN was really generated from the phone number.
EXAMPLE
Number : 0241194000 LENGHT(10)
PIN : 675436 LENGHT(6) ONLY NUMERIC
Checker : 673AA3738SHZXCVDER ANY LENGTH ALPHANUMERIC.
Any links or help will be great.
What you are looking for a mathematical bijective function (preferably a complex one)
that allows any Number (x) to be turned into a PIN, by means of said function
F(Number) = PIN
By having an bijective function, you can validate PINs by solving the equation in the opposite direction.
http://en.wikipedia.org/wiki/Bijection
For example:
Given the function: F(Number) = Number*2
function GeneratePIN(Number)
return Number*2
end
function validatePIN(PIN,Number)
return PIN == Number*2
end
Notwithstanding the correct comments above about that you can not create a unique PIN that is shorter than its source set (it boils down to hashing, which is by definition never unique), I'm assuming you mean a "code that cannot be reproduced for the phone number by an outsider, and that, given the phone number and the PIN, can be proven to be related, while accepting that the same PIN might also be valid when used with another phone number".
Assuming that, the easiest solution is to create a salted hash from the phone number. Sample pseudocode:
static uniqueHash = '9t45uufg92dit093ik,96igm0v9m6i09im09i309disl54923';
function createPinFromPhone(string phonenumber)
{
string pin = '';
do {
hash = md5(phonenumber+uniqueHash);
pin += extractNumbersFromString(hash);
phonenumber = pin+hash;
}
while(pin.length < 6)
return pin.subString(0, 6);
}
This is a (rough) example of a function that will always return the same pin code from the same phone number, and through the use of the unique secret key can never be reproduced by an outsider. Theoretically you could have an entropy problem, but not on this scale realistically.
If you just want to create a PIN from a phone number (where the phone number is unique and PIN is not necessarily unique), you can use one of the many hashing functions, such as CRC32, MD5, SHA1, ... and take just the number of bytes/numbers you need.
Note that it is not simple to make it secure (if you want that) since hashing functions are usually only making it harder to figure out the original value (in your case figuring out the number from the PIN) and not vice versa.

Coupon code generation

I would like to generate coupon codes , e.g. AYB4ZZ2. However, I would also like to be able to mark the used coupons and limit their global number, let's say N. The naive approach would be something like "generate N unique alphanumeric codes, put them into database and perform a db search on every coupon operation."
However, as far as I realize, we can also attempt to find a function MakeCoupon(n), which converts the given number into a coupon-like string with predefined length.
As far as I understand, MakeCoupon should fullfill the following requirements:
Be bijective. It's inverse MakeNumber(coupon) should be effectively computable.
Output for MakeCoupon(n) should be alphanumeric and should have small and constant length - so that it could be called human readable. E.g. SHA1 digest wouldn't pass this requirement.
Practical uniqueness. Results of MakeCoupon(n) for every natural n <= N should be totally unique or unique in the same terms as, for example, MD5 is unique (with the same extremely small collision probability).
(this one is tricky to define) It shouldn't be obvious how to enumerate all remaining coupons from a single coupon code - let's say MakeCoupon(n) and MakeCoupon(n + 1) should visually differ.
E.g. MakeCoupon(n), which simply outputs n padded with zeroes would fail this requirement, because 000001 and 000002 don't actually differ "visually".
Q:
Does any function or function generator, which fullfills the following requirements, exist? My search attempts only lead me to [CPAN] CouponCode, but it does not fullfill the requirement of the corresponding function being bijective.
Basically you can split your operation into to parts:
Somehow "encrypt" your initial number n, so that two consecutive numbers yield (very) different results
Construct your "human-readable" code from the result of step 1
For step 1 I'd suggest to use a simple block cipher (e.g. a Feistel cipher with a round function of your choice). See also this question.
Feistel ciphers work in several rounds. During each round, some round function is applied to one half of the input, the result is xored with the other half and the two halves are swapped. The nice thing about Feistel ciphers is that the round function hasn't to be two-way (the input to the round function is retained unmodified after each round, so the result of the round function can be reconstructed during decryption). Therefore you can choose whatever crazy operation(s) you like :). Also Feistel ciphers are symmetric, which fulfills your first requirement.
A short example in C#
const int BITCOUNT = 30;
const int BITMASK = (1 << BITCOUNT/2) - 1;
static uint roundFunction(uint number) {
return (((number ^ 47894) + 25) << 1) & BITMASK;
}
static uint crypt(uint number) {
uint left = number >> (BITCOUNT/2);
uint right = number & BITMASK;
for (int round = 0; round < 10; ++round) {
left = left ^ roundFunction(right);
uint temp = left; left = right; right = temp;
}
return left | (right << (BITCOUNT/2));
}
(Note that after the last round there is no swapping, in the code the swapping is simply undone in the construction of the result)
Apart from fulfilling your requirements 3 and 4 (the function is total, so for different inputs you get different outputs and the input is "totally scrambled" according to your informal definition) it is also it's own inverse (thus implicitely fulfilling requirement 1), i.e. crypt(crypt(x))==x for each x in the input domain (0..2^30-1 in this implementation). Also it's cheap in terms of performance requirements.
For step 2 just encode the result to some base of your choice. For instance, to encode a 30-bit number, you could use 6 "digits" of an alphabet of 32 characters (so you can encode 6*5=30 bits).
An example for this step in C#:
const string ALPHABET= "AG8FOLE2WVTCPY5ZH3NIUDBXSMQK7946";
static string couponCode(uint number) {
StringBuilder b = new StringBuilder();
for (int i=0; i<6; ++i) {
b.Append(ALPHABET[(int)number&((1 << 5)-1)]);
number = number >> 5;
}
return b.ToString();
}
static uint codeFromCoupon(string coupon) {
uint n = 0;
for (int i = 0; i < 6; ++i)
n = n | (((uint)ALPHABET.IndexOf(coupon[i])) << (5 * i));
return n;
}
For inputs 0 - 9 this yields the following coupon codes
0 => 5VZNKB
1 => HL766Z
2 => TMGSEY
3 => P28L4W
4 => EM5EWD
5 => WIACCZ
6 => 8DEPDA
7 => OQE33A
8 => 4SEQ5A
9 => AVAXS5
Note, that this approach has two different internal "secrets": First, the round function together with the number of rounds used and second, the alphabet you use for encoding the encyrpted result. But also note, that the shown implementation is in no way secure in a cryptographical sense!
Also note, that the shown function is a total bijective function, in the sense, that every possible 6-character code (with characters out of your alphabet) will yield a unique number. To prevent anyone from entering just some random code, you should define some kind of restictions on the input number. E.g. only issue coupons for the first 10.000 numbers. Then, the probability of some random coupon code to be valid would be 10000/2^30=0.00001 (it would require about 50000 attempts to find a correct coupon code). If you need more "security", you can just increase the bit size/coupon code length (see below).
EDIT: Change Coupon code length
Changing the length of the resulting coupon code requires some math: The first (encrypting) step only works on a bit string with even bit count (this is required for the Feistel cipher to work).
In the the second step, the number of bits that can be encoded using a given alphabet depends on the "size" of chosen alphabet and the length of the coupon code. This "entropy", given in bits, is, in general, not an integer number, far less an even integer number. For example:
A 5-digit code using a 30 character alphabet results in 30^5 possible codes which means ld(30^5)=24.53 bits/Coupon code.
For a four-digit code, there is a simple solution: Given a 32-Character alphabet you can encode *ld(32^4)=5*4=20* Bits. So you can just set the BITCOUNT to 20 and change the for loop in the second part of the code to run until 4 (instead of 6)
Generating a five-digit code is a bit trickier and somhow "weakens" the algorithm: You can set the BITCOUNT to 24 and just generate a 5-digit code from an alphabet of 30 characters (remove two characters from the ALPHABET string and let the for loop run until 5).
But this will not generate all possible 5-digit-codes: with 24 bits you can only get 16,777,216 possible values from the encryption stage, the 5 digit codes could encode 24,300,000 possible numbers, so some possible codes will never be generated. More specifically, the last position of the code will never contain some characters of the alphabet. This can be seen as a drawback, because it narrows down the set of valid codes in an obvious way.
When decoding a coupon code, you'll first have to run the codeFromCoupon function and then check, if bit 25 of the result is set. This would mark an invalid code that you can immediately reject. Note that, in practise, this might even be an advantage, since it allows a quick check (e.g. on the client side) of the validity of a code without giving away all internals of the algorithm.
If bit 25 is not set you'll call the crypt function and get the original number.
Though I may get docked for this answer I feel like I need to respond - I really hope that you hear what I'm saying as it comes from a lot of painful experience.
While this task is very academically challenging, and software engineers tend to challenge their intelect vs. solving problems, I need to provide you with some direction on this if I may. There is no retail store in the world, that has any kind of success anyway, that doesn't keep very good track of each and every entity that is generated; from each piece of inventory to every single coupon or gift card they send out those doors. It's just not being a good steward if you are, because it's not if people are going to cheat you, it's when, and so if you have every possible item in your arsenal you'll be ready.
Now, let's talk about the process by which the coupon is used in your scenario.
When the customer redeems the coupon there is going to be some kind of POS system in front right? And that may even be an online business where they are then able to just enter their coupon code vs. a register where the cashier scans a barcode right (I'm assuming that's what we're dealing with here)? And so now, as the vendor, you're saying that if you have a valid coupon code I'm going to give you some kind of discount and because our goal was to generate coupon codes that were reversable we don't need a database to verify that code, we can just reverse it right! I mean it's just math right? Well, yes and no.
Yes, you're right, it's just math. In fact, that's also the problem because so is cracking SSL. But, I'm going to assume that we all realize the math used in SSL is just a bit more complex than anything used here and the key is substantially larger.
It does not behoove you, nor is it wise for you to try and come up with some kind of scheme that you're just sure nobody cares enough to break, especially when it comes to money. You are making your life very difficult trying to solve a problem you really shouldn't be trying to solve because you need to be protecting yourself from those using the coupon codes.
Therefore, this problem is unnecessarily complicated and could be solved like this.
// insert a record into the database for the coupon
// thus generating an auto-incrementing key
var id = [some code to insert into database and get back the key]
// base64 encode the resulting key value
var couponCode = Convert.ToBase64String(id);
// truncate the coupon code if you like
// update the database with the coupon code
Create a coupon table that has an auto-incrementing key.
Insert into that table and get the auto-incrementing key back.
Base64 encode that id into a coupon code.
Truncate that string if you want.
Store that string back in the database with the coupon just inserted.
What you want is called Format-preserving encryption.
Without loss of generality, by encoding in base 36 we can assume that we are talking about integers in 0..M-1 rather than strings of symbols. M should probably be a power of 2.
After choosing a secret key and specifying M, FPE gives you a pseudo-random permutation of 0..M-1 encrypt along with its inverse decrypt.
string GenerateCoupon(int n) {
Debug.Assert(0 <= n && n < N);
return Base36.Encode(encrypt(n));
}
boolean IsCoupon(string code) {
return decrypt(Base36.Decode(code)) < N;
}
If your FPE is secure, this scheme is secure: no attacker can generate other coupon codes with probability higher than O(N/M) given knowledge of arbitrarily many coupons, even if he manages to guess the number associated with each coupon that he knows.
This is still a relatively new field, so there are few implementations of such encryption schemes. This crypto.SE question only mentions Botan, a C++ library with Perl/Python bindings, but not C#.
Word of caution: in addition to the fact that there are no well-accepted standards for FPE yet, you must consider the possibility of a bug in the implementation. If there is a lot of money on the line, you need to weigh that risk against the relatively small benefit of avoiding a database.
You can use a base-36 number system. Assume that you want 6 characters in the coupen output.
pseudo code for MakeCoupon
MakeCoupon(n)
{
Have an byte array of fixed size, say 6. Initialize all the values to 0.
convert the number to base - 36 and store the 'digits' in an array
(using integer division and mod operations)
Now, for each 'digit' find the corresponding ascii code assuming the
digits to start from 0..9,A..Z
With this convension output six digits as a string.
}
Now the calculating the number back is the reverse of this operation.
This would work with very large numbers (35^6) with 6 allowed characters.
Choose a cryptographic function c. There are a few requirements on c, but for now let us take SHA1.
choose a secret key k.
Your coupon code generating function could be, for number n:
concatenate n and k as "n"+"k" (this is known as salting in password management)
compute c("n"+"k")
the result of SHA1 is 160bits, encode them (for instance with base64) as an ASCII string
if the result is too long (as you said it is the case for SHA1), truncate it to keep only the first 10 letters and name this string s
your coupon code is printf "%09d%s" n s, i.e. the concatenation of zero-padded n and the truncated hash s.
Yes, it is trivial to guess n the number of the coupon code (but see below). But it is hard to generate another valid code.
Your requirements are satisfied:
To compute the reverse function, just read the first 9 digits of the code
The length is always 19 (9 digits of n, plus 10 letters of hash)
It is unique, since the first 9 digits are unique. The last 10 chars are too, with high probability.
It is not obvious how to generate the hash, even if one guesses that you used SHA1.
Some comments:
If you're worried that reading n is too obvious, you can obfuscate it lightly, like base64 encoding, and alternating in the code the characters of n and s.
I am assuming that you won't need more than a billion codes, thus the printing of n on 9 digits, but you can of course adjust the parameters 9 and 10 to your desired coupon code length.
SHA1 is just an option, you could use another cryptographic function like private key encryption, but you need to check that this function remains strong when truncated and when the clear text is provided.
This is not optimal in code length, but has the advantage of simplicity and widely available libraries.

can int store string value in c#

I am working on the front end of an application. I have to introduce one more filter criteria LoanNumber. Now loan number is E-100. Business layer and domain object is not in my control. So i cannot change it. Domain object which holds loannumber is integer, I have to do
ingeoFilterData.intLoanNumber="E-100"
ingeoFilterData is the domain object. intLoanNumber is declared as Nullable Int32 Now this domainobject is very critical and it goes to some external engine,so i cannot change it.
Please suggest some workaround.
Edit-
I am copying down loannumber from database table.
RT1
RT2
PT1
pt10
PT11
PT12
PT13
PT14
PT15
pt16
pt17
pt8
pt9
MDR1
MDR2
MDR3
If you have only one character, you can do this:
multiply your int by 100. (for example E-51 -> 5100)
Then keep the char as int in the rest of the number (for example 5106).
Do the reverse when you need to show the UI id (E-51).
If you have no limitations (as you mentioned) then you can have your int as a protocol (according to me that is even harder because you are limited by Int32 - 4,294,967,296).
You can set your number to something like
<meaning><number><meaning><number>
and meaning is - 1 - number, 2 - letter, 3 - hyphon.
then 11 will mean 1; 201 will mean A, 3 will mean hyphon, and 113201 will mean 1-A;
It's complicated and not very likely to be usable...
This solution limits your id to length of 5 numbers or 3 letters and 1 number. You can squeez some more by using your int bit-wize and optimize your "protocol" as much as possible.
I hope this helps,
Danail
Is "E-100" a string. ie. E is not a variable?
No, you can't set an int to a string value.
No, an int type cannot store a string. But you can parse your value to an int, before passing this to your domain object for filtering.
If the "prefix" of the loan number is always "E-" you could just exclude it.
Otherwise maybe you could add a property "LoanNumberPrefix" and store the "E-" in it.
Unfortunately at some point, bad design will give you unsolvable problems.
I don't know if this is one of them, but if the domain model has specified that loan numbers are integers, then either you, or the people that made that model clearly hasn't done their job.
Why the E in there? What does it signify? Is it just a prefix, can you remove it when storing it and put it back before displaying it?
Unfortunately, if the prefix can change, so that at some point you will have F-100 and so on, then you need to find a way to encode that into the integer you send to the domain model and business logic.
If you can't do that, you need to find a different place to store that prefix, or possibly the entire code.
If you can't do that, well, then you're screwed.
But to be blunt, this smells badly of someone who has been asleep while designing.
"Yeah, that's a good idea, we'll make the loan identification number an integer. I know somewhere, someplace, that someone has an example of what those loan identification numbers look like, but it's just numbers right? I mean, what could go wrong...?"
i think thats possible if you can convert the char into ASCII code.
string --- ASCII
0-10---48-57
A-Z----65-90
a-z----97-122
check out the ASCII table for more info..
Conversion:
so you can convert
RT1 to 082084049
RT2 to 082084050 and
MDR3 to 077068082051
i just prepend 0's to each character if the value is not 3 digit one(because max possible ASCII (z) value is in 3 digits ). R is actually 82, it becomes 082. And the final integer (no of digits) would be in multiples of 3.
Extraction:
This helps to extract the info in the other end. just split this into seperate 3 digit values and convert them to char and append them. you wil get the final string.
082,084,049 - R,T,1. thats all.
p.s: this method may end up in arithmetic overflow problem for large strings
I suggest that you talk to someone in the business/domain layer, or who is responsible for the design of the system, and point out to them that loannumber need to be changed to a string. No one will thank you for bodging your code to get around what is a design flaw--it can only lead to trouble and confusion later.

Categories