Decimal to Binary Conversion Error - binary

How do you fix the following problem converting from decimal to binary?
void tobinary(int bin) {
string binary = Convert.ToInt32(bin, 2);
}
These are the errors:
Error 2: Argument 2: cannot convert from 'int' to 'System.IFormatProvider' 42
Error 1: The best overloaded method match for 'System.Convert.ToInt32(object, System.IFormatProvider)' has some invalid arguments 42

see:
Decimal to binary conversion in c #
it should be:
void tobinary(int bin) {
string binary = Convert.ToString(bin, 2);}

Related

How can I convert a bitstring to the binary form in Julia

I am using bitstring to perform an xor operation on the ith bit of a string:
string = bitstring(string ⊻ 1 <<i)
However the result will be a string, so I cannot continue with other i.
So I want to know how do I convert a bitstring (of the form “000000000000000000000001001”) to (0b1001)?
Thanks
You can use parse to create an integer from the string, and then use string (alt. bitstring)to go the other way. Examples:
julia> str = "000000000000000000000001001";
julia> x = parse(UInt, str; base=2) # parse as UInt from input in base 2
0x0000000000000009
julia> x == 0b1001
true
julia> string(x; base=2) # stringify in base 2
"1001"
julia> bitstring(x) # stringify as bits (64 bits since UInt64 is 64 bits)
"0000000000000000000000000000000000000000000000000000000000001001"
don't use bitstring. You can either do the math with a BitVector or just a UInt. No reason to bring a String into it.

How to set precision for json_real while doing json_dump using jansson library

If a double value of 8.13 is passed into json_real and dump the json i see that its printing 8.1300000000000008, Is there any way to get 8.13 or 8.13000000000000000 exactly in C?
double test = 8.13;
json_t* msgtest = json_object();
json_object_set_new(msgtest, "test", json_real(test));
char* msgStr;
msgStr = json_dumps(msgtest, 0);
You can use JSON_REAL_PRECISION, introduced in jansson 2.7.
Output all real numbers with at most n digits of precision. The valid
range for n is between 0 and 31 (inclusive), and other values result
in an undefined behavior.
By default, the precision is 17, to correctly and losslessly encode
all IEEE 754 double precision floating point numbers.
Consider the following program:
#include <jansson.h>
int main() {
double test = 8.13;
json_t* msgtest = json_object();
json_object_set_new(msgtest, "test", json_real(test));
printf("%s\n", json_dumps(msgtest, JSON_REAL_PRECISION(3)));
}
It prints
{"test": 8.13}

How to create a TCL variable of type bytearray

I am using TCL 8.4.20.
So I have the following code:
set a [binary format H2 1]
set b [binary format H2 2]
set c [binary format H2 3]
set bytes $a
append bytes $a
append bytes $b
append bytes $c
puts $bytes
I set a breakpoint at Tcl_PutsObjCmd() function in TCL's C source code and I see its argument, $bytes, is of type string while I expect it to be bytearray.
Question 1:Why is that? From the first assignment to the final appending, "bytes" accepts nothing but binary data.
The reason I do this experiment is, we have a TCL extension command in C, it expects the command argument is of byte array type - it has a check the value's typePtr should be tclByteArrayType. My TCL code currently fails on this command because the data passed to the command is of type string, just as demo'ed above.
I googled around, seems the "right" way to make a byte array object is to have every byte ready first and finally use one "binary format" command to put all into one. But it is a fairly big change to my current TCL code.
Question 2: Given that I already have a TCL variable whose data are all binaries (created using "binary format" for each byte and put together using "append") while its type is string, How can I change its internal type to "bytearray" through some TCL maneuvering?
Technically, the internal type is not a guaranteed property. Everything is a string. The code may shimmer a type away whenever it feels like. And code that depends on the internal type is usually very brittle or outright broken.
So your C code should call Tcl_GetByteArrayFromObj() instead of peeking at the arguments internals. That does the proper conversion if the object has not yet a byteArray representation.
About your questions:
Why doesn't append of two byte arrays keep the byte array type?
It does, at least for 8.6, if you do it right and never trigger the creation of a string rep.
Running this in tkcon, the append turns the value into a string:
() 98 % set a [binary format H2 1]

() 99 % set b [binary format H2 1]

() 100 % ::tcl::unsupported::representation $a
value is a bytearray with a refcount of 2, object pointer at 0000000005665420, internal representation 000000000587B280:0000000005665240, string representation ""
() 101 % ::tcl::unsupported::representation $b
value is a bytearray with a refcount of 2, object pointer at 000000000564EEB0, internal representation 000000000587B4A0:00000000056590E0, string representation ""
() 102 % set x $a

() 103 % ::tcl::unsupported::representation $x
value is a bytearray with a refcount of 4, object pointer at 0000000005665420, internal representation 000000000587B280:0000000005665240, string representation ""
() 104 % append x $b

() 105 % ::tcl::unsupported::representation $x
value is a string with a refcount of 3, object pointer at 0000000005663F50, internal representation 0000000005896BA0:000000000564F030, string representation ""
this happens, because the bytearray has a string rep (due to Tkcon echoing the value) created. The append optimization only works for 'pure' bytearrays, e.g. bytearrays that do not have a string rep. This is similar to some optimizations for 'pure' lists.
So it works like this, preventing the shimmering result echo:
() 106 % set b [binary format H2 1]; puts "pure"
pure
() 107 % set a [binary format H2 1]; puts "pure"
pure
() 108 % set x $a; puts "pure"
pure
() 109 % ::tcl::unsupported::representation $a
value is a bytearray with a refcount of 3, object pointer at 0000000005658780, internal representation 000000000587B320:0000000005658CF0, no string representation
() 110 % ::tcl::unsupported::representation $b
value is a bytearray with a refcount of 2, object pointer at 000000000564ED60, internal representation 000000000587B500:0000000005658750, no string representation
() 111 % ::tcl::unsupported::representation $x
value is a bytearray with a refcount of 3, object pointer at 0000000005658780, internal representation 000000000587B320:0000000005658CF0, no string representation
() 112 % append x $b; puts "pure"
pure
() 113 % ::tcl::unsupported::representation $x
value is a bytearray with a refcount of 2, object pointer at 0000000005658690, internal representation 00000000058A5C60:0000000005658960, no string representation
Note the no string representation part.
How to turn a string into a bytearray
Just do a binary format:
set x [binary format a* $x]

How to assign a char in Xtend?

How can a variable of type char be assigned? I am looking for the Xtend equivalent of javas:
char c='?';
In Xtend the compiler reject all quotation marks like ' or " because they produce a String:
var char c='?';
^ Error: Incompatible types. Expected char or java.lang.Character but was java.lang.String
Xtext Version is 2.2
Since 2.4 you can write:
val char c = '?'
Currently you have to use '?'.charAt(0).

Get data with a c program from an HTML form

I have created the following C program to get data from an HTML form. But when I try to compile and run it, I get:
segmentation fault 11 (core dumped)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
char *N1,*N2,*N3,*N4,*N5;
int cgi_length;
char *cgi_data;
printf("Content-type:text/html\n\n");
cgi_length=atoi(getenv("CONTENT_LENGTH"));
cgi_data=malloc(cgi_length+1);
fread(cgi_data,1,cgi_length,stdin);
printf("<HTML>");
printf("<HEAD><TITLE>DATA</TITLE></HEAD><BODY>\n");
printf("<H3>DATA</H3>\n");
if(cgi_data == NULL)
{
printf("<P>Error! Error in passing data from form to script.");
}
else {
printf("%s",cgi_data);
sscanf(cgi_data,"N1=%s&N2=%s&N3=%S&N4=%SN5=%s",&N1,&N2,&N3,&N4,&N5);
printf("<P>N1 is %s and N2 is %s and N3 is %S and N4 is %S and N5 is %s.",N1,N2,N3,N4,N5);
}
}
Also if I use the ls command to see the data in the cgi-bin directory I see that a file named myprogram.cgi.core is created.
Does anyone know what is wrong?
I had the same problem before. I used fgets in a while loop. fread didn't work for me. Try this:
cgi_length=atoi(getenv("CONTENT_LENGTH"));
cgi_data=malloc(cgi_length+1);
while(fgets(cgi_data,cgi_length,stdin)!=NULL){
//insert some processing here
}
You have to check that the return value of your getenv function call is not a null pointer. Passing a null pointer to atoi is undefined behavior. I suggest also to check the return value of all your function calls and to use strtol function instead of atoi because atoi cannot detect errors.
Load the coredump in GDB. Try something like:
gdb myprogram.cgi myprogram.cgi.core
maybe replace myprogram.cgi with the proper name of the CGI.
When you are in GDB you could get a back trace to see where the application crashed by typing bt in the console.
Here you can find a quick tutorial on howto GDB: http://cs.baylor.edu/~donahoo/tools/gdb/tutorial.html
Few notes...:
Check what getenv returns, maybe it returns NULL instead of the value of the environment variable.
sscanf copies the values of the strings to the buffers where N1 N2 N3 N4 N5 are pointing to, it would be wise to allocate some memory for those pointers first...
You don't have to get the reference of the points N1 N2 N3 N4 N5
As Daniel Fischer noted: fread doesn't 0 terminate the string.
If you compile with -Wall (all warnings), it will give you an idea what's wrong
cgi.c: In function ‘main’:
cgi.c:23:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘char **’ [-Wformat]
cgi.c:23:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 4 has type ‘char **’ [-Wformat]
cgi.c:23:9: warning: format ‘%S’ expects argument of type ‘wchar_t *’, but argument 5 has type ‘char **’ [-Wformat]
cgi.c:23:9: warning: format ‘%S’ expects argument of type ‘wchar_t *’, but argument 6 has type ‘char **’ [-Wformat]
cgi.c:23:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 7 has type ‘char **’ [-Wformat]
cgi.c:24:9: warning: format ‘%S’ expects argument of type ‘wchar_t *’, but argument 4 has type ‘char *’ [-Wformat]
cgi.c:24:9: warning: format ‘%S’ expects argument of type ‘wchar_t *’, but argument 5 has type ‘char *’ [-Wformat]
cgi.c:26:1: warning: control reaches end of non-void function [-Wreturn-type]
There are several fundamental C programming errors. Use e.g. lint to find out some of them. For example, you’re declaring N1 as a character pointer but do not initialize it, and you pass its address as argument. You need to allocate a character array somehow and pass a pointer to it as an argument to sscanf.
I am pretty sure that you are getting zero in this line
cgi_length=atoi(getenv("CONTENT_LENGTH"));
Check if there is this environment variable actually defined. And always check for sizes before allocating memory and before putting some data into it.