How can I get values from a json string? - c

Let's say I had a string that contains:
{"ticker":{"high":8.976,"low":8.843,"avg":8.9095,"vol":2096.78,"last":8.845,"buy":8.946,"sell":8.843,"server_time":1343686701}}
How would I take the numbers and put them into a separate variable?
For example :
int high = 8.976
int low = 8.843
/* and so on */

Lots of ways.
"sscanf" is one alternative.
The standard string functions "strstr()", "atof()", etc are another.
I'd recommend finding a good JSON-parsing library. For example:
http://www.digip.org/jansson/

Related

Array to use for appending unknown number of bytes into single large array in System verilog

I am trying to append unknown number of bytes into a single large array . Which array type should I use ? I am trying to this
len=temp_i.len()
for(i=0;i<len;i++)begin
bit [7:0] temp_ascii;
temp_ascii=temp_i.getc(i);
arr = {arr,temp_ascii};
where temp_i is an input srting. My Final aim is convert input String into binary representation of its ASCII value and concatenate them together into a single large array.
I having a hard time choosing what kind of array to use dynamic or associative or if I can use queue.
Any help will be highly appreciable.
You use associative arrays when the index values are not consecutive, or the ordering is meaningless. Not applicable here.
You use queues when adding or removing one element at a time to an array. If arr was declared as a queue, you could write
string temp_i;
bit [7:0] arr[$];
int len;
len = temp_i.len();
for(int i=0,i<len;i++)
arr.push_back(temp_i.getc(i));
If your strings are small, or you plan to concatenate many strings together, a queue is your best option. But if you only plan to convert one string to an array, then using a bit-stream cast to a dynamic array will be the most efficient.
string temp_i;
typedef bit [7:0] uint8_da_t[]; // typedef required for cast to target
uint8_da_t arr; // using typedef not required here, but A VERY GOOD IDEA
arr = uint8_da_t'(temp_i);
is it supposed to be a synthesizable code or a test bench?
None of the above is synthesizable.
you would do it differently in different worlds.

Text adventure game--randomly connecting rooms together - C

I'm trying to create a text adventure game that 7 rooms, with the information saved in files. This question IS similar to Connect Rooms Randomly in Adventure Game however the answer didn't exactly help me. I've gone about my program in a different way than that OP so I'm not sure how to use that answer to help me.
The idea is you have 7 rooms, named say A, B, C, D, E, F, and G. After the rooms are created, I need to randomly connect them to each other. Each room needs between 3 and 6 random connections. If room A is connected to B, C, and D, each of those rooms should be connected to A. This information is then saved to a file which is read later.
The code I have for this section so far is:
char *connections[7];
int j = 0;
int randomRoom;
for (j = 0; j <= randConnections; j++) {
randomRoom = rand() % 10;
if (randomRoom == randName) {
randomRoom = rand() % 10;
} else {
connections[j] = names[randomRoom];
}
randConnections is a random int between 3 and 6, defined earlier in the code. names is a string array that holds the names of the rooms, also defined earlier in my program.
I am pretty new to C (I'm mostly experienced with Java) so I can't figure it out. I should mention, this is all in one function defined as:
void createRooms(FILE *fp)
I know there are probably more efficient ways to do this, but at this point I'm just trying to get the code working and deal with efficiency later.
I've done a ton of googling and am honestly beating my head against the wall right now. Any help would be greatly appreciated. If there's any more code I should post or any other information let me know.
C-style strings can get a bit confusing. A "string" in pure C is a char array. Arrays in C are strongly related to pointers. In fact, instead of defining
char myCString[6] = "hello";
You could define
char * myCString = "hello";
In fact, in the first case, myCString used alone will just return a pointer to the first element. The [] operator is just a convenient dereference and increment operator. So &(myCString+1) becomes myCString[1]
So long story short, your "string" array in C is really an array of char* - pointers to the first element of an array of characters
You're trying to assign this to a single character, which doesn't make logical sense. If you mean for the connections to truly be strings, do like kcraigie says.
Here's some backup I found, I'm afraid there are more nuances and I'm not an expert, but that's the gist - https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays#Pointers_and_Arrays
This may seem absurd coming from java - that's C for ya. C++'s standard library includes a string construct like what you'd be familiar with. It's a class that wraps a "raw" C array and controls access to it and manages it like Java and C# strings. Modern C++ best practices try to stay away from the raw arrays. You'll also notice that nothing stops you from calling MyCString[4000], which is just going to grab a piece of memory from the middle of nowhere and do heaven knows what. There is no bounds checking on raw arrays in C. Be careful!

good way to map enums to strings in C

I have a bunch of enums (from libvirt library if you are wondering) that look like this:
enum whatever {
VAL_A = 1
VAL_B = 2
...
}
How do I convert these to meaningful strings? That is, VAL_A has a state meaning "meaning_A", VAL_B has a state meaning "meaning_B" and so on. In php or perl or python, I would generate a key:val pair and return the results in O(1) time. Is there an efficient way to map these to meaningful strings in C? I was thinking of a switch statement, but was wondering about better approaches.
Thanks,
Vik.
Try using it as an array index:
char *strs[] = {"meaning_A", "meaning_B", "etc."};
strs[(int)enumvar - 1];

Need suggestion on Code conversion to Matlab_extension 2

This is an extension of the previously asked question: link. In a short, I am trying to convert a C program into Matlab and looking for your suggestion to improve the code as the code is not giving the correct output. Did I convert xor the best way possible?
C Code:
void rc4(char *key, char *data){
://Other parts of the program
:
:
i = j = 0;
int k;
for (k=0;k<strlen(data);k++){
:
:
has[k] = data[k]^S[(S[i]+S[j]) %256];
}
int main()
{
char key[] = "Key";
char sdata[] = "Data";
rc4(key,sdata);
}
Matlab code:
function has = rc4(key, data)
://Other parts of the program
:
:
i=0; j=0;
for k=0:length(data)-1
:
:
out(k+1) = S(mod(S(i+1)+S(j+1), 256)+1);
v(k+1)=double(data(k+1))-48;
C = bitxor(v,out);
data_show =dec2hex(C);
has = data_show;
end
It looks like you're doing bitwise XOR on 64-bit doubles. [Edit: or not, seems I forgot bitxor() will do an implicit conversion to integer - still, an implicit conversion may not always do what you expect, so my point remains, plus it's far more efficient to store 8-bit integer data in the appropriate type rather than double]
To replicate the C code, if key, data, out and S are not already the correct type you can either convert them explicitly - with e.g. key = int8(key) - or if they're being read from a file even better to use the precision argument to fread() to create them as the correct type in the first place. If this is in fact already happening in the not-shown code then you simply need to remove the conversion to double and let v be int8 as well.
Second, k is being used incorrectly - Matlab arrays are 1-indexed so either k needs to loop over 1:length(data) or (if the zero-based value of k is used as i and j are) then you need to index data by k+1.
(side note: who is x and where did he come from?)
Third, you appear to be constructing v as an array the same size of data - if this is correct then you should take the bitxor() and following lines outside the loop. Since they work on entire arrays you're needlessly repeating this every iteration instead of doing it just once at the end when the arrays are full.
As a general aside, since converting C code to Matlab code can sometimes be tricky (and converting C code to efficient Matlab code very much more so), if it's purely a case of wanting to use some existing non-trivial C code from within Matlab then it's often far easier to just wrap it in a MEX function. Of course if it's more of a programming exercise or way to explore the algorithm, then the pain of converting it, trying to vectorise it well, etc. is worthwhile and, dare I say it, (eventually) fun.

custom data type in C

I am working with cryptography and need to use some really large numbers. I am also using the new Intel instruction for carryless multiplication that requires m128i data type which is done by loading it with a function that takes in floating point data as its arguments.
I need to store 2^1223 integer and then square it and store that value as well.
I know I can use the GMP library but I think it would be faster to create two data types that both store values like 2^1224 and 2^2448. It will have less overhead.I am going to using karatsuba to multiply the numbers so the only operation I need to perform on the data type is addition as I will be breaking the number down to fit m128i.
Can someone direct me in the direction towards material that can help me create the size of integer I need.
If you need your own datatypes (regardless of whether it's for math, etc), you'll need to fall back to structures and functions. For example:
struct bignum_s {
char bignum_data[1024];
}
(obviously you want to get the sizing right, this is just an example)
Most people end up typedefing it as well:
typedef struct bignum_s bignum;
And then create functions that take two (or whatever) pointers to the numbers to do what you want:
/* takes two bignums and ORs them together, putting the result back into a */
void
bignum_or(bignum *a, bignum *b) {
int i;
for(i = 0; i < sizeof(a->bignum_data); i++) {
a->bignum_data[i] |= b->bignum_data[i];
}
}
You really want to end up defining nearly every function you might need, and this frequently includes memory allocation functions (bignum_new), memory freeing functions (bignum_free) and init routines (bignum_init). Even if you don't need them now, doing it in advance will set you up for when the code needs to grow and develop later.

Resources