C# Arabic to English Code gives me error - asp.net

can some one help me to rectify this error i have am using VS2010 ASP.Net C#3.0 i found this could on net but it is not working as it give me the error as show in the Screen shot. I am not able to understand the error message
Code reference from http://weblogs.asp.net/abdullaabdelhaq/archive/2009/06/27/displaying-arabic-number.aspx
CODE :
protected void Button1_Click(object sender, System.EventArgs e)
{ //Call Function
this.Label1.Text = "Arabic Number : <b>" + TranslateNumerals(this.TextBox1.Text) + "</b>";
}
public static string TranslateNumerals(string sIn)
{
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decoder = null;
utf8Decoder = enc.GetDecoder();
dynamic sTranslated = new System.Text.StringBuilder();
char[] cTransChar = new char[2];
byte[] bytes = {217,160 };
// Start Converting characters into Arabic mode.
char[] aChars = sIn.ToCharArray();
foreach (char c in aChars)
{
if (char.IsDigit(c))
{
bytes[1] = 160 + Convert.ToInt32(char.GetNumericValue(c));
utf8Decoder.GetChars(bytes, 0, 2, cTransChar, 0);
sTranslated.Append(cTransChar[0]);
}
else
{
sTranslated.Append(c);
}
}
return sTranslated.ToString();
}

The compiler is complaining about your request to implicitly convert the result of the integer addition (160 + Convert.ToInt32...) to a byte. This is a narrowing conversion; integers have a wider range than bytes do, and the compiler wants you to acknowledge, with an explicit cast operator, that you're aware that this could produce runtime errors.
Assuming that adding 160 actually does something useful to a character, I'd advise using something like this instead.
if (c >= '0' && c <= '9')
{
bytes[i] = (byte)((int)c + 160);
}
...which will properly produce, as the i'th value of the array bytes, a byte with a value 160 greater than the char c, if c represents an ASCII digit between 0 and 9.
Don't use the function char.IsDigit, which will return true even if c is a digit outside of the ASCII digit range. I don't run into this much, but since you're explicitly writing multilingual code, you'll want to handle that case.
I haven't reviewed the rest of the post you link to, but given these two quite obvious errors, I wouldn't put much faith in the correctness of the rest of it, frankly.

You could add a cast like (byte) in front of the 160.
I'm a little confused why such a large function is required to do that.
Updated answer:
Given that there are only 10 possible numerals to convert between, you can do something like this to make it slightly more readable. I think, anyway, I don't usually code in c#, and I'm on a mac right now... feel free to bash my code.
public static string TranslateNumerals(string sIn)
{
var sb = new System.Text.StringBuilder();
char[] arabic = { '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'};
foreach (char c in sIn) {
int idx;
// if it wasn't a number, just append it, otherwise convert it
if(!Integer.tryParse("" + c, idx)) {
sb.Append(c);
} else {
sb.Append(arabic[idx]);
}
}
return sb.toString();
}
// backwards array (which appears frontwards here)
{ '٩','٨','٧','٦','٥','٤','٣', '٢', '١', '٠'};

Related

Recieving two sets of string-data from Processing to Arduino into two variables

I'm desperatly trying to get arduino to divide a string from processing into two sets of variables. In the code below I've decided to just type the important parts but x and y does of course contain the correct values. Any solution would be appreciated. These are my two attempts so far:
Attempt 1 doesn't work at all.
1.Processing:
myPort.write(x + "," + y + "\n");
1.Arduino:
String tempX = Serial.readStringUntil(44);
String tempY = Serial.readStringUntil(10);
String x = tempX.substring(0,tempX.length() -1);
String y = tempY.substring(0,tempY.length() -1);
Attempt 2 where x works correctly but not y.
2.Processing:
String [] dataToSend = new String [2];
dataToSend [0] = x;
dataToSend [1] = y;
String joinedData = join(dataToSend, ":");
myPort.write(joinedData);
2.Arduino:
String x = Serial.readStringUntil(":");
Serial.read(); //next character is comma, so skip it using this
String y = Serial.readStringUntil('\0');
First, don't worry about combining them on the Processing side. Sending two strings one right after the other is the same as sending one long string. It's all being broken into bytes on the Serial line and nobody can tell where one print line stops and the next starts.
myport.write(x);
myport.write(',');
myport.write(y);
myport.write('\n')
will work just as good.
Then on the Arduino side you most likely want to shy away from the String class. Read the data character by character into a char array.
char myArray[howLongTheStringIs];
char x[howLongXIs];
char y[howLongYIs];
int index = 0;
This gets called over and over in loop and picks up serial data as it comes in:
while (Serial.available()){
char c = Serial.read();
myArray[index] = c; // add c to the string
myArray[++index] = 0; // null terminate our string
if(c == '\n'){ // if we are at the end of the string
handleString();
}
}
Then you have a function to parse your string there are lots of ways to do that:
If you don't know anything about the strings other than the separator use strtok:
void handleString(){
char* ptr = strtok(myArray, ":"); // get up to the ":" from the string
strcpy(x, ptr); // copy into x
ptr = strtok(NULL, "\n"); // get from the separator last time up to the next "\n"
strcpy(y, ptr); // copy into y
index = 0 // reset our index and
myArray[0] = 0; // and clear the string
}
That's all untested and uncompiled and written in the reply box, so if I made a little typo in there please forgive and correct. But something like this should work. If you already know the exact lengths of the strings (or can send them from the processing code) then the handleString method can be simpler. If you've got something short to do with x and y and don't need them after that then maybe you can just keep pointers to where they are in myArray. It all depends on what the larger picture goal of your code is. But something like this should get the job done.

Arduino command parsing

I am writing an ESP32 project which receives an UDP packet and based on it some action should be carried out. There are those commands:
FON
FOFF
MSC <INT> <INT>
TC <INT>
I receive the message like this:
void receiveUdpMessages(){
int udpMsgLength = Udp.parsePacket();
if(udpMsgLength != 0){
byte udpPacket[udpMsgLength+1];
IPAddress senderIp = Udp.remoteIP();
Udp.read(udpPacket, udpMsgLength);
udpPacket[udpMsgLength] = 0;
Udp.flush();
Serial.println("Received UDP Message from : " + String(senderIp[0]) + "." + String(senderIp[1]) + "." + String(senderIp[2])+ "."+ String(senderIp[3]));
processReceivedMessage((char *)udpPacket);
}
}
and this is the processReceivedMessage method:
void processReceivedMessage(char *message){
if(strncmp("FON",message,3)==0){
setParameters(ct, 100);
}else if(strncmp("FOFF",message,4)==0){
setParameters(ct, 0);
}else if(strncmp("MSC",message,3)==0){
}else if(strncmp("TC",message,2)==0){
}
}
My question is what is the best way to split both of the ints for the parameterized commands? Also if you notice any sort of issue with above code please tell me I did not have an opportunity to test it yet.
So there's actually two seperate steps here:
Find where the integers substrings start in your message
Convert those substrings to actual ints
For step 1, there are many ways to do this, but using strchr is probably the easiest for your purposes.
For step 2, either use atoi or the safer-but-harder-to-use strtol
Here's an example for the MSC message, the one for processing the TC message will be very similar.
I've kept it as one function for clarity, but there's scope for refactoring it.
void process_msc_message(char * message)
{
int integers[2];
// strchr returns a pointer to the space character
char* substring = strchr(message, ' ');
if (substring)
{
// atoi will convert the first number it finds in the given string
integers[0] = atoi(substring);
}
// Jump forward to the next number
substring = strchr(substring+1, ' ');
if (substring)
{
integers[1] = atoi(substring);
}
// Do something with the integers...
}

Making smaller lower-higher console game

So im a pretty new programmer so forgive me if i make any mistakes.
I need to make a higher or lower game for my class but im a little bit stuck now.
The purpose of this whole game is to guess the number which is random generated by the computer. But here's the tricky part, the user only needs to get 8 chances to guess the number right. If not the game must end and print something like: you lost, the number was.....
I came this far;
public static void main(String[] args) {
int timesGuessed = 0;
int randomNummer = (int)(Math.random()*100);
int number;
boolean won = true;
Scanner input = new Scanner(System.in);
do{
System.out.print("Guess the number: ");
number = input.nextInt();
timesGuessed++;
if(timesGuessed == 8){
won = false;
}
if(number > randomNummer){
System.out.println("Lower!");
}
else if(number < randomNummer){
System.out.println("Higher!");
}
}
while(number != randomNummer);
if(won == true){
System.out.println("The number is guessed right in " + timesGuessed + " attemts.");
}
else{
System.out.println("You lost. The number was " + randomNummer + ".");
}
}
Now the game lets you finish even though you already had 8 chances. Thats what i want to change. It needs to stop when you failed the eight time.
Thank you for the help, it would be very appreciated.
You also need to check your won variable in the condition of your loop. You may also want to add an else so it doesn't print "Higher" or "Lower" after the final try.

extract a letter from a string in processing

im trying to get a letter from a string in processing
so lets say the sketch receives the string "x193" it would need to be able to isolate the x and the 193 and put them in different variables.
You don't really need to get and put the 'x' as it is always the same, so just get what is after it, until the end of the string. Something like:
String[] a = {"x1", "x12", "x123"};
String[] onlyNumbers = new String[3];
void setup(){
for (int i = 0; i length; i++){
String stirp = a[i].substring(a[i].indexOf('x')+1, a[i].length());
onlyNumbers[i] = stirp;
}
println(onlyNumbers);
}
If you need performance you can also use StringBuilder, wich is much faster.
You need something like this:
String inQuestion = "x193";
String myCharacter = inQuestion.substring(0, 1);
See http://www.processing.org/reference/String_substring_.html

how to binary to qpixmap

I find it difficult to translate binary into picture, I use a pixmap.
transfer into the binary is correct but when I show using this program actually does not work.
this is my code:
if (binaryNumber[0]==1)ui->led16->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led16->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[1]=1) ui->led15->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led15->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[2]==1)ui->led14->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led14->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[3]==1)ui->led13->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led13->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[4]==1)ui->led12->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led12->setPixmap(QPixmap("../../picture/ball-gray.png"));
bool ok2 = false;
QByteArray binaryNumber = QByteArray::number(DO.toLongLong(&ok2, 16), 2);
qDebug()<<binaryNumber<<binaryNumber[0]<<binaryNumber[1]<<binaryNumber[2 <<binaryNumber[3];
i.e
binaryNumber =1011
binaryNumber[0] = 1
binaryNumber[1] = 0
binaryNumber[2] = 1
binaryNumber[3] = 1
but when
binaryNumber =100
binaryNumber[0] = 1
binaryNumber[1] = 0
binaryNumber[2] = 0
so when i use a pixmap, then led the flame does not correspond to the binary number because array [0] is different when the size is different.
is there any simple code for me?
Your use of a QByteArray to store bits of a number is unnecessary. In C/C++, you can access the bits directly by doing a bitwise AND (&) with a mask.
template <typename T> static QPixmap setPixmap(T * p, int value, int bitNo)
{
const bool bit = value & (1<<bitNo);
p->setPixmap(bit ? QPixmap("../../picture/ball-yellow.png")
: QPixmap("../../picture/ball-gray.png"));
}
void Class::setDisplay(int val)
{
setPixmap(ui->led12, val, 0);
setPixmap(ui->led13, val, 1);
setPixmap(ui->led14, val, 2);
setPixmap(ui->led15, val, 3);
setPixmap(ui->led16, val, 4);
}
Note that QByteArray::number() returns alphanumeric characters ('0' = 48, '1' = 49 etc.), not characters with the numerical values 0, 1 etc. This is an important difference!
If you do binaryNumber = QByteArray::number(value, 2), this returns a byte array like for example "1010". Thus, binaryNumber[0] == '1', NOT binaryNumber[0] == 1:
if (binaryNumber[0]=='1')ui->led16->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led16->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[1]=='1')ui->led15->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led15->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[2]=='1')ui->led14->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led14->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[3]=='1')ui->led13->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led13->setPixmap(QPixmap("../../picture/ball-gray.png"));
if (binaryNumber[4]=='1')ui->led12->setPixmap(QPixmap("../../picture/ball-yellow.png"));
else ui->led12->setPixmap(QPixmap("../../picture/ball-gray.png"));
Note that your code is riddled with redundant code lines, resulting in bad quality software. You should try to write the code above in a loop or at least move out the pixmaps. Moving the pixmap initialisations in some static variables or in the constructor of the containing class results in some performance boost, too.
So your class could look similar to this: (I only included the relevant parts, of course, there also has to be the code for the UI stuff.)
class LEDNumberView
{
private:
// member variables:
QPixmap bitOn;
QPixmap bitOff;
// helper function
inline QPixmap getBitPixmap(bool bitVal)
{
return bitVal ? bitOn : bitOff;
}
public:
// constructor
LEDNumberView()
{
QString path = "../../picture/ball-%1.png";
bitOn = QPixmap(path.arg("yellow"));
bitOff = QPixmap(path.arg("gray"));
}
// call whenever you want to change the binary number displayed by the LEDs
void setBinaryNumber(int value)
{
QByteArray binaryNumber = QByteArray::number(value, 2);
ui->led16->setPixmap(getBitPixmap(binaryNumber[0] == '1'));
ui->led15->setPixmap(getBitPixmap(binaryNumber[1] == '1'));
ui->led14->setPixmap(getBitPixmap(binaryNumber[2] == '1'));
ui->led13->setPixmap(getBitPixmap(binaryNumber[3] == '1'));
ui->led12->setPixmap(getBitPixmap(binaryNumber[4] == '1'));
ui->led11->setPixmap(getBitPixmap(binaryNumber[5] == '1'));
}
};
To combine the answer of Kuba Ober with mine, write the setBinaryNumber function as he suggested. It's up to you which method of binary conversion you prefer - bit manipulation (use his method) or convert to and then work with bytes (yours).

Resources