Convert TextBox string to Byte - visual-c++

how to convert TextBox string value to Byte. I have:
array<Byte>^ mybytes = gcnew array<Byte>{6,2,1};
mybytes[1] = motor1ForwardTextBox->Text->System::IConvertible::ToByte;
System::Diagnostics::Debug::Write(mybytes[1]);
but there is error in second line:
Error 2 error C2440: '=' : cannot convert from 'unsigned char (__clrcall System::IConvertible::* )(System::IFormatProvider ^)' to 'unsigned char' c:\users\guest4\documents\avr\serial2\serial2\Form1.h 563 1 serial2 (Visual Studio 2010)

A straightforward way is:
mybytes[1] = Byte::Parse(motor1ForwardTextBox->Text);
After all, the nature of the conversion you want is parsing decimal digits.
Either way you'll get exceptions if the characters are not digits with optional + and -, or the value is not in the range 0 to 255. And, unfortunately, even though parsing to Byte does not accept "," or ".", the acceptable digit characters do depend on the culture. So, if necessary, pass an IFormatProvider.

String does an explicit implementation of the IConvertible::ToByte method, so you'll need to cast it.
And of course, you'll need to actually call the method. That error message is saying that it can't convert from a method that returns unsigned char, to an unsigned char.
mybytes[1] = dynamic_cast<IConvertible^>(motor1ForwardTextBox->Text)->ToByte();
^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^

Related

Is there any easy way to replace %20 by a space in a CString?

I need to replace some %20 by spaces and got compile errors which i do not understand:
CString str = _T("foo%20bar");
str.Replace('%20',' '); // C4305 argument: truncation from 'int' to 'wchar_t'
str.Replace(_T('%20'),_T(' ')); // C4305 argument: truncation from 'int' to 'wchar_t'
str.Replace(_T("%20"),_T(" ")); // C2664 'int ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::Replace(const wchar_t *,const wchar_t *)': cannot convert argument 1 from 'const char [4]' to 'wchar_t'
What is wrong?
The CString::Replace() method takes null-terminated string pointers as input, not individual characters. Your string literals need to use " instead of ', eg:
CString str = _T("foo%20bar");
str.Replace(_T("%20"), _T(" "));
Note that matches your last example, which you say is also erroring. The only way that can fail with the error message you have shown is if you have a misconfiguration in your project, where UNICODE is defined 1 but _UNICODE is not defined 2.
1: as evident by CString being mapped to CStringT<wchar_t>.
2: as evident by the compiler saying _T("%20") is a const char[] rather than a const wchar_t[].
CString uses TCHAR from the Win32 API, not _TCHAR from the C runtime library. Usually they are interchangeable, but not so in your situation. So, you need to either fix your project's configuration so that _UNICODE is also defined, or else use the Win32 TEXT() macro to match CString's use of TCHAR:
CString str = TEXT("foo%20bar");
str.Replace(TEXT("%20"), TEXT(" "));
Or, simply stop using TCHAR-based APIs altogether (TCHAR dates back to the days of Win9x/ME when Microsoft was pushing everyone to start migrating their code to Unicode), and really should not be used in modern coding if you can avoid it. Just use wchar_t strings directly instead, eg:
CStringW str = L"foo%20bar";
str.Replace(L"%20", L" ");
The last one should have worked, except that you seem to have a wide CString in a project without the UNICODE and/or _UNICODE macro defined.
In this combination, the _T() macro isn't giving you a compatible string literal. But L"whatever" will.
str.Replace(L"%20", L" ");
Notice that this does what you asked, but is not adequate for URL unescaping. You should convert all %xx sequences.
%20 may be formatted string like %d. and Replace function return replaced String and str is not replaced.
try like: str = str.Replace(_T("%%20"), _T(" "));
or
try like: str = str.Replace(_T("%20"),_T(" "));
Extra Info
If you look at this Format specification syntax: printf and wprintf functions article you will see the following clarification:
A basic conversion specification contains only the percent sign and a type character. For example, %s specifies a string conversion. To print a percent-sign character, use %%. ...

Convert large decimal number to hexadecimal notation

When creating a String object in Swift you can use a String Format Specifier to convert an integer to hexadecimal notation.
print(String(format:"%x", 1234))
// output: 4d2
// expected output: 4d2
But when numbers become bigger, the output is not as expected.
print(String(format:"%x", 12345678901234))
// output: 73ce2ff2
// expected output: b3a73ce2ff2
It seems that the output of String(format:"%x", n) is truncated at 8 characters. I don't think in hexadecimal natively, this makes debugging hard. I have seen answers for other programming languages where it is explained that you need to brake-up the large integer into parts, but that seems wrong to me.
What am I doing wrong here?
What is the right way to convert decimal numbers to hexadecimal numbers in Swift?
You need to use %lx or %llx
print(String(format:"%lx", 12345678901234))
b3a73ce2ff2
Table 2 on the site you linked specifies them
l -
Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a long or unsigned long argument.
x is for unsigned 32 bit integers which only go up to 4.294.967.296

Problems assigning char string to char array

I have already read all prior answers regarding my problem. However, I'm not a very bright coder to am unable to grasp it. Could someone please look into my problem.
I am trying to write a CSV file using entries from a 2D array. string.h has already been included in main().
void create_marks_csv(int rout[][20],float p[][20],float c[][20],int n)
{
system("cls");
char str1[100],str2[100],str3[100];
printf("\nEnter filename for routing matrix: ");
gets(str1);
printf("\n Creating %s.csv file",str1);
FILE *fp;
int i,j;
str1=strcat(str1,".csv");
str1=strcat("C:\\Users\\Neil\\Documents\\Trust CSV Logs\\",str1) ;
fp=fopen(str1,"w+");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
fprintf(fp,"X");
else
fprintf(fp,"%d",rout[i][j]);
}
fprintf(fp,"\n");
}
fclose(fp);
printf("\nFile created: %s",str1);
system("cls");
}
The warnings and errors are as follows:
5 20 C:\Users\Neil\Documents\main.c [Warning] extra tokens at end of #include directive [enabled by default]
C:\Users\Neil\Documents\main.c In function 'create_marks_csv':
168 6 C:\Users\Neil\Documents\main.c [Error] incompatible types when assigning to type 'char[100]' from type 'char *'
169 6 C:\Users\Neil\Documents\main.c [Error] incompatible types when assigning to type 'char[100]' from type 'char *'
28 C:\Users\Neil\Documents\Makefile.win recipe for target 'main.o' failed
Every time you write str1 =, you are telling the compiler to change str1 so that it points to whatever location in memory is found on the right-hand side of the = sign. But you declared char str1[100], which means that str1, interpreted as a pointer, can only point to the start of the block of 100 characters at the location where this declaration allocated them. So it makes no sense to write str1 =.
Passing a C string constant as the first argument of strcat is likely to be a disaster, although the compiler seems not to mind. The first argument of strcat should be a character buffer big enough to hold the results of the concatenation. In order to concatenate something onto the end of a constant string, you can allocate a buffer big enough, then copy the constant string to it, then call strcat.
In general you can probably do whatever you need to do without using the return value of strcat, that is, no need to ever write strcat on the right-hand side of =.
It is advisable to use fgets instead of gets because then you can protect against the possibility that you will get too much input to fit in your allocated character buffer. If you allocate 100 characters in your largest buffer, you can only afford to accept 95 characters minus the length of the string "C:\\Users\\Neil\\Documents\\Trust CSV Logs\\". (The other 5 characters are required to hold the string ".csv" and the terminating null character).
I saw also that you declare str2 and str3 but I didn't see where you used either of them. It looks like you don't need both of them, but you might find it convenient to use str2 as the buffer for your last concatenation of strings.

(char)NULL , '\0' and 0 all mean the same thing in C's memset?

We are migrating a 32 bit application from rhel 5.3 to 6.4
We are getting an warning "Cast from pointer to integer of different size " on new system's memset.
Do (char)NULL, '\0' and 0 all mean the same thing in C's memset?
The following code is giving the warning in new environment.
#define NULLC (char)NULL
#define MAX_LEN 11
…
memset(process_name, NULLC, MAX_LEN + 1);
strncpy(process_name, "oreo", MAX_LEN);
The do not all mean the same thing, though they're likely to yield the same result.
(char)NULL converts the value of NULL, which is an implementation-defined null pointer constant, to char. The type of NULL may be int, or void*, or some other integer type. If it's of an integer type, the conversion is well defined and yields 0. If it's void*, you're converting a null pointer value to char, which has an implementation-defined result (which is likely, but not guaranteed, to be 0).
The macro NULL is intended to refer to a null pointer value, not a null character, which is a very different thing.
Your macro NULLC is not particularly useful. If you want to refer to a null character, just use the literal constant '\0'. (And NULLC is IMHO too easily confused with NULL.)
The other two constants, '\0' and 0, have exactly the same type (int) and value (zero).
(It's admittedly counterintutive that '\0' has type int rather than char. It's that way for historical reasons, and it rarely matters. In C++, character constants are of type char, but you asked about C.)
They all have the same value 0 but they don't mean the same thing.
(char)NULL - You are casting the value of NULL pointer to character with value 0
'\0' - End of string character with value 0 (NUL)
0 - 32 bit integer with value 0.
You are getting a warning because somewhere in your code you're likely using something like:
short somevar = NULL;
or something similar.
0 and '\0' are both the integer 0 (the type of a character literal is int, not char), so they are exactly equivalent. The second argument to memset is an int, from which only the low-order 8 bits will be used.
NULL is a different beast. It is a pointer type that is guaranteed by the standard to be different from any pointer to a real object. The standard does NOT say that this is done by giving it the value 0, though it must compare equal to zero. Also, it may be of different width than int, so passing it as the second argument to memset() might not compile.
In defining NULLC, you are casting NULL from a native pointer (64-bits, probably defined as (void*)0) to char (8-bits). If you wanted to declare NULLC, you should just do
#define NULLC 0
and do away with NULL and the (char). The formal argument to memset is int, not char.
0 = zero of int datatype
'\0' = (char)0 //null char
NULL = (void*)0 //null pointer
See how they are interlinked to each other. Gcc often gives warnings for all the typecast that are implicitly done by the compiler.
You are using
#define NULLC (char)NULL
.....
memset(process_name, NULLC, MAX_LEN + 1);
equivalent to:
memset(process_name, (char)NULL, MAX_LEN + 1);
equivalent to:
memset(process_name, '\0', MAX_LEN + 1);
You are passing char data (ie; '\0' ) as second parameter where "unsigned int" data is accepted. So compiler is converting it to unsigned int implicilty and thus giving typecast warning. You can simply ignore it or change it as:
memset(process_name, 0, MAX_LEN + 1);

How to define Empty Char in Delphi

Just for curiosity,
Why in Delphi, if we defined an empty char by:
a:Char;
a:='';
we get an error: Incompatible types: 'Char' and 'string'
However, if we placed
a:='a';
it will be fine?
Is it necessary to define an empty char by: a:=#0?
A char is a single (that is, exactly one) character. So 'a', '∫', and '⌬' are all OK, but not 'ab' (a two-character string), 'Hello World!' (a twelve-character string), or '' (a zero-character string).
However, the NULL character (#0) is a character like any other.
In addition, the character datatype is implemented as a word (in modern versions of Delphi), that is, as two bytes. If all these values 0, 1, ..., 2^16 - 1 are used for real characters, how in the world would you represent your 'empty char'?
There is no such thing as an empty char. A char has to have a value. It is an ordinal type, a simple value type. Just as an integer, say, always has a value, so does a char.
The value #0 is not an empty char, it is the character with value 0, commonly known as NUL.

Resources