language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | /* Capstone Disassembler Engine */
/* By Nguyen Anh Quynh <[email protected]>, 2013-2019 */
#include <stdio.h>
#include <capstone/platform.h>
#include <capstone/capstone.h>
struct platform {
cs_arch arch;
cs_mode mode;
unsigned char* code;
size_t size;
const char* comment;
};
static csh handle;
static void print_string_hex(const char* comment, unsigned char* str, size_t len)
{
unsigned char *c;
printf("%s", comment);
for (c = str; c < str + len; c++) {
printf("0x%02x ", *c & 0xff);
}
printf("\n");
}
const char* s_addressing_modes[] = {
"<invalid mode>",
"Register Direct - Data",
"Register Direct - Address",
"Register Indirect - Address",
"Register Indirect - Address with Postincrement",
"Register Indirect - Address with Predecrement",
"Register Indirect - Address with Displacement",
"Address Register Indirect With Index - 8-bit displacement",
"Address Register Indirect With Index - Base displacement",
"Memory indirect - Postindex",
"Memory indirect - Preindex",
"Program Counter Indirect - with Displacement",
"Program Counter Indirect with Index - with 8-Bit Displacement",
"Program Counter Indirect with Index - with Base Displacement",
"Program Counter Memory Indirect - Postindexed",
"Program Counter Memory Indirect - Preindexed",
"Absolute Data Addressing - Short",
"Absolute Data Addressing - Long",
"Immediate value",
};
static void print_read_write_regs(cs_detail* detail)
{
int i;
for (i = 0; i < detail->regs_read_count; ++i)
{
uint16_t reg_id = detail->regs_read[i];
const char* reg_name = cs_reg_name(handle, reg_id);
printf("\treading from reg: %s\n", reg_name);
}
for (i = 0; i < detail->regs_write_count; ++i)
{
uint16_t reg_id = detail->regs_write[i];
const char* reg_name = cs_reg_name(handle, reg_id);
printf("\twriting to reg: %s\n", reg_name);
}
}
static void print_insn_detail(cs_insn *ins)
{
cs_m68k* m68k;
cs_detail* detail;
int i;
// detail can be NULL on "data" instruction if SKIPDATA option is turned ON
if (ins->detail == NULL)
return;
detail = ins->detail;
m68k = &detail->m68k;
if (m68k->op_count)
printf("\top_count: %u\n", m68k->op_count);
print_read_write_regs(detail);
printf("\tgroups_count: %u\n", detail->groups_count);
for (i = 0; i < m68k->op_count; i++) {
cs_m68k_op* op = &(m68k->operands[i]);
switch((int)op->type) {
default:
break;
case M68K_OP_REG:
printf("\t\toperands[%u].type: REG = %s\n", i, cs_reg_name(handle, op->reg));
break;
case M68K_OP_IMM:
printf("\t\toperands[%u].type: IMM = 0x%x\n", i, (int)op->imm);
break;
case M68K_OP_MEM:
printf("\t\toperands[%u].type: MEM\n", i);
if (op->mem.base_reg != M68K_REG_INVALID)
printf("\t\t\toperands[%u].mem.base: REG = %s\n",
i, cs_reg_name(handle, op->mem.base_reg));
if (op->mem.index_reg != M68K_REG_INVALID) {
printf("\t\t\toperands[%u].mem.index: REG = %s\n",
i, cs_reg_name(handle, op->mem.index_reg));
printf("\t\t\toperands[%u].mem.index: size = %c\n",
i, op->mem.index_size ? 'l' : 'w');
}
if (op->mem.disp != 0)
printf("\t\t\toperands[%u].mem.disp: 0x%x\n", i, op->mem.disp);
if (op->mem.scale != 0)
printf("\t\t\toperands[%u].mem.scale: %d\n", i, op->mem.scale);
printf("\t\taddress mode: %s\n", s_addressing_modes[op->address_mode]);
break;
case M68K_OP_FP_SINGLE:
printf("\t\toperands[%u].type: FP_SINGLE\n", i);
printf("\t\t\toperands[%u].simm: %f\n", i, op->simm);
break;
case M68K_OP_FP_DOUBLE:
printf("\t\toperands[%u].type: FP_DOUBLE\n", i);
printf("\t\t\toperands[%u].dimm: %lf\n", i, op->dimm);
break;
case M68K_OP_REG_BITS:
printf("\t\toperands[%u].type: REG_BITS = $%x\n", i, op->register_bits);
break;
case M68K_OP_REG_PAIR:
printf("\t\toperands[%u].type: REG_PAIR = (%s, %s)\n", i,
cs_reg_name(handle, op->reg_pair.reg_0),
cs_reg_name(handle, op->reg_pair.reg_1));
break;
}
}
printf("\n");
}
static void test()
{
#define M68K_CODE "\x4C\x00\x54\x04\x48\xe7\xe0\x30\x4C\xDF\x0C\x07\xd4\x40\x87\x5a\x4e\x71\x02\xb4\xc0\xde\xc0\xde\x5c\x00\x1d\x80\x71\x12\x01\x23\xf2\x3c\x44\x22\x40\x49\x0e\x56\x54\xc5\xf2\x3c\x44\x00\x44\x7a\x00\x00\xf2\x00\x0a\x28\x4E\xB9\x00\x00\x00\x12\x4E\x75"
struct platform platforms[] = {
{
CS_ARCH_M68K,
(cs_mode)(CS_MODE_BIG_ENDIAN | CS_MODE_M68K_040),
(unsigned char*)M68K_CODE,
sizeof(M68K_CODE) - 1,
"M68K",
},
};
uint64_t address = 0x01000;
cs_insn *insn;
int i;
size_t count;
for (i = 0; i < sizeof(platforms)/sizeof(platforms[0]); i++) {
cs_err err = cs_open(platforms[i].arch, platforms[i].mode, &handle);
if (err) {
printf("Failed on cs_open() with error returned: %u\n", err);
abort();
}
cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON);
count = cs_disasm(handle, platforms[i].code, platforms[i].size, address, 0, &insn);
if (count) {
size_t j;
printf("****************\n");
printf("Platform: %s\n", platforms[i].comment);
print_string_hex("Code: ", platforms[i].code, platforms[i].size);
printf("Disasm:\n");
for (j = 0; j < count; j++) {
printf("0x%" PRIx64 ":\t%s\t%s\n", insn[j].address, insn[j].mnemonic, insn[j].op_str);
print_insn_detail(&insn[j]);
}
printf("0x%" PRIx64 ":\n", insn[j-1].address + insn[j-1].size);
// free memory allocated by cs_disasm()
cs_free(insn, count);
} else {
printf("****************\n");
printf("Platform: %s\n", platforms[i].comment);
print_string_hex("Code:", platforms[i].code, platforms[i].size);
printf("ERROR: Failed to disasm given code!\n");
abort();
}
printf("\n");
cs_close(&handle);
}
}
int main()
{
test();
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* :::::::: */
/* ft_flag_precision.c :+: :+: */
/* +:+ */
/* By: aholster <[email protected]> +#+ */
/* +#+ */
/* Created: 2019/10/03 21:32:49 by aholster #+# #+# */
/* Updated: 2019/10/05 13:15:47 by jesmith ######## odam.nl */
/* */
/* ************************************************************************** */
#include "./../incl/ft_flag_parser.h"
#include <limits.h>
static int ft_isdigit_internal(const char c)
{
if (c >= '0' && c <= '9')
return (1);
return (0);
}
static void precision_num_parse(const char *const restrict format,\
size_t *aindex,\
t_flag *const restrict flags)
{
size_t subdex;
unsigned int num;
num = 0;
subdex = *aindex;
while (ft_isdigit_internal(format[subdex]) == 1)
{
num += (format[subdex] - '0');
if (ft_isdigit_internal(format[subdex + 1]) == 1)
num *= 10;
subdex++;
}
flags->precision = num;
*aindex = subdex;
}
static void precision_arg_extract(va_list args,\
t_flag *const restrict flags)
{
int num;
num = va_arg(args, int);
if (num >= 0)
{
ft_turn_on_flag('.', flags);
flags->precision = num;
}
}
void ft_flag_precision(const char *const restrict format,\
size_t *const restrict aindex,\
t_writer *const restrict clipb)
{
t_flag *const restrict flags = clipb->flags;
size_t subdex;
subdex = (*aindex) + 1;
if (format[subdex] == '*')
{
precision_arg_extract(clipb->args, flags);
subdex++;
}
else if (format[subdex] >= '0' && format[subdex] <= '9')
{
precision_num_parse(format, &subdex, flags);
ft_turn_on_flag('.', flags);
}
else
{
flags->precision = 0;
ft_turn_on_flag('.', flags);
}
*aindex = subdex;
}
|
C | //double log10(double x) 返回log10x的值
#include<stdio.h>
#include<math.h>
int main()
{
int t;
scanf("%d",&t);
while(t--){
double sum;
int i,n;
sum=0;
scanf("%d",&n);
for(i=2;i<=n;i++)
sum+=log10(i);
printf("%d\n",(int)sum+1);
}
return 0;
}
|
C | #include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "linkedlist.h"
int main(int argc, char **argv)
{
ll_t list = makeList();
assert(list.head == NULL);
int val = 7;
push(&list, &val);
assert(*(int *)list.head->data == 7);
assert(list.head->next == NULL);
assert(*(int *)pop(&list) == 7);
assert(list.head == NULL);
int newval = 19;
push(&list, &val);
push(&list, &newval);
assert(*(int *)list.head->data == 19);
assert(*(int *)list.head->next->data == 7);
assert(list.head->next->next == NULL);
assert(*(int *)pop(&list) == 19);
assert(*(int *)list.head->data == 7);
assert(list.head->next == NULL);
assert(*(int *)pop(&list) == 7);
assert(list.head == NULL);
int anotherval = 113;
push(&list, &val);
push(&list, &newval);
pushBack(&list, &anotherval);
assert(*(int *)list.head->data == 19);
assert(*(int *)list.head->next->data == 7);
assert(*(int *)list.head->next->next->data == 113);
assert(*(int *)pop(&list) == 19);
assert(*(int *)list.head->data == 7);
assert(*(int *)list.head->next->data == 113);
assert(*(int *)pop(&list) == 7);
assert(*(int *)list.head->data == 113);
assert(*(int *)pop(&list) == 113);
assert(list.head == NULL);
puts("All tests passed");
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* syntax_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nscarab <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/28 17:31:34 by nscarab #+# #+# */
/* Updated: 2021/03/19 17:08:15 by nscarab ### ########.fr */
/* */
/* ************************************************************************** */
int only_spaces_after(char *str, int i)
{
if (!str)
return (1);
while (str[++i])
{
if (str[i] != ' ' && str[i] != '\t')
return (0);
}
return (1);
}
int only_signes_after(char *str, int i)
{
if (!str)
return (1);
while (str[++i])
{
if (str[i] != ' ' && str[i] != '\t' && str[i] != '|'
&& str[i] != ';' && str[i] != '>' && str[i] != '<')
return (0);
}
return (1);
}
int only_spaces_before(char *str, int i)
{
if (!str)
return (1);
while (--i >= 0)
{
if (str[i] != ' ' || str[i] != '\t')
return (0);
}
return (1);
}
int is_mirrored(char *str, int i)
{
int count;
count = 0;
while (--i >= 0)
{
if (str[i] == '\\')
count++;
else
break ;
}
if (count % 2 == 0)
return (0);
else
return (1);
}
int ends_with_semicolon(char *str)
{
int count;
count = 0;
if (!str || !*str)
return (0);
while (str[count + 1])
count++;
if (str[count] == ';')
return (1);
return (0);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Array
{
// int pointer for the Array of integer type
// int *A;
int A[20];
int size;
int length;
};
void DisplayArrayElements(struct Array arr)
{
int i;
printf("\nElements are:\n");
for(i=0; i<arr.length; i++)
{
printf("%d\n",arr.A[i]);
}
}
void Append(struct Array *arr, int element)
{
//Check if the length of the elements in array is less than size of the array
if(arr->length<arr->size)
{
//Insert element at the end of the array elements. Increment the length
arr->A[arr->length++] = element;
}
}
void Insert(struct Array *arr, int index, int element)
{
int i;
if(index>=0 && index<=arr->length)
{
for(i=arr->length; i>index; i--)
{
arr->A[i] = arr->A[i-1];
}
arr->A[index] = element;
arr->length++;
}
}
int Delete(struct Array *arr, int index)
{
int i;
if(index >=0 && index <arr->length)
{
int x = arr->A[index];
for(i=index; i<arr->length-1;i++)
{
arr->A[i] = arr->A[i+1];
}
arr->length--;
return x;
}
return 0;
}
int LinearSearch(struct Array arr, int key)
{
int i;
for(i=0; i<arr.length; i++)
{
if(arr.A[i] == key)
{
return i;
}
}
return -1;
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int LinearSearch_transposition(struct Array *arr, int key)
{
int i;
for(i=0; i<arr->length; i++)
{
if(arr->A[i] == key)
{
swap(&arr->A[i], &arr->A[i-1]);
return i;
}
}
return -1;
}
int LinearSearch_movetohead(struct Array *arr, int key)
{
int i;
for(i=0; i<arr->length; i++)
{
if(arr->A[i] == key)
{
swap(&arr->A[i], &arr->A[0]);
return i;
}
}
return -1;
}
int BinarySearch(struct Array arr, int key)
{
int l, mid, h;
l = 0;
h = arr.length-1;
while(l<=h)
{
mid = (l+h)/2;
if(key == arr.A[mid])
{
return mid;
}
else if(key < arr.A[mid])
{
h = mid-1;
}
else
{
l = mid+1;
}
}
return -1;
}
int RecurciveBinarySearch(int a[], int l, int h, int key)
{
int mid;
if(l<=h)
{
mid = (l+h)/2;
if(key == a[mid])
{
return mid;
}
else if(key < a[mid])
{
return RecurciveBinarySearch(a, l, mid-1, key);
}
else
{
return RecurciveBinarySearch(a, mid+1, h, key);
}
}
return -1;
}
int Get(struct Array arr, int index)
{
if(index>=0 && index<arr.length)
{
return arr.A[index];
}
return -1;
}
void Set(struct Array *arr, int index, int x)
{
if(index>=0 && index<arr->length)
{
arr->A[index] = x;
}
}
int Max(struct Array arr)
{
int max = arr.A[0];
int i;
for(i=0; i<arr.length; i++)
{
if(arr.A[i]>max)
{
max = arr.A[i];
}
}
return max;
}
int Min(struct Array arr)
{
int min = arr.A[0];
int i;
for(i=0; i<arr.length; i++)
{
if(arr.A[i]<min)
{
min = arr.A[i];
}
}
return min;
}
int Sum(struct Array arr)
{
int total = 0;
int i;
for(i=0; i<arr.length; i++)
{
total += arr.A[i];
}
return total;
}
float Avg(struct Array arr)
{
return (float)Sum(arr)/arr.length;
}
void LeftShift_Reverse(struct Array *arr)
{
int *B;
int i,j;
B = (int *)malloc(sizeof(arr->length*sizeof(int)));
for(i=0,j=arr->length-1; i<arr->length; i++, j--)
{
B[j] = arr->A[i];
}
for(i=0; i<arr->length; i++)
{
arr->A[i] = B[i];
}
}
void LeftShift_Reverse2(struct Array *arr)
{
int i,j;
int temp;
for(i=0, j=arr->length-1; i<j; i++, j--)
{
swap(&arr->A[i], &arr->A[j]);
}
}
bool isSorted(struct Array *arr, int length)
{
int i;
for(i=0; i<length-1; i++)
{
if(arr->A[i]>arr->A[i+1])
{
return false;
}
}
return true;
}
void insertsort(struct Array *arr, int ele)
{
int i=arr->length-1 ;
if(arr->length == arr->size)
{
return;
}
while(i>=0 && arr->A[i]>ele)
{
arr->A[i+1] = arr->A[i];
i--;
}
arr->A[i+1] = ele;
arr->length++;
}
void rearrange_posandneg(struct Array *arr)
{
int i=0, j= arr->length-1;
while(i<j)
{
while(arr->A[i]<0)
{
i++;
}
while(arr->A[j]>=0)
{
j--;
}
if(i<j)
{
swap(&arr->A[i], &arr->A[j]);
}
}
}
struct Array* MergeArrays(struct Array *arr1, struct Array *arr2)
{
int i, j, k;
i=j=k=0;
struct Array *arr3 = (struct Array *)malloc(sizeof(struct Array));
while(i<arr1->length && j<arr2->length)
{
if(arr1->A[i]<arr2->A[j])
{
arr3->A[k++] = arr1->A[i++];
}
else
{
arr3->A[k++] = arr2->A[j++];
}
}
for(;i<arr1->length; i++)
{
arr3->A[k++] = arr1->A[i];
}
for(;j<arr2->length; j++)
{
arr3->A[k++] = arr2->A[j];
}
arr3->length = arr1->length + arr2->length;
arr3->size = 10;
return arr3;
}
struct Array* SetUnion(struct Array *arr1, struct Array *arr2)
{
int i, j, k;
i=j=k=0;
struct Array *arr3 = (struct Array *)malloc(sizeof(struct Array));
while(i<arr1->length && j<arr2->length)
{
if(arr1->A[i]<arr2->A[j])
{
arr3->A[k++] = arr1->A[i++];
}
else if(arr2->A[j]<arr1->A[i])
{
arr3->A[k++] = arr2->A[j++];
}
else
{
arr3->A[k++] = arr1->A[i++];
j++;
}
}
for(;i<arr1->length; i++)
{
arr3->A[k++] = arr1->A[i];
}
for(;j<arr2->length; j++)
{
arr3->A[k++] = arr2->A[j];
}
arr3->length = k;
arr3->size = 10;
return arr3;
return arr3;
}
struct Array* SetIntersection(struct Array *arr1, struct Array *arr2)
{
int i, j, k;
i=j=k=0;
struct Array *arr3 = (struct Array *)malloc(sizeof(struct Array));
while(i<arr1->length && j<arr2->length)
{
if(arr1->A[i]<arr2->A[j])
{
i++;
}
else if(arr2->A[j]<arr1->A[i])
{
j++;
}
else if(arr2->A[j] == arr1->A[i])
{
arr3->A[k++] = arr1->A[i++];
j++;
}
}
arr3->length = k;
arr3->size = 10;
return arr3;
return arr3;
}
struct Array* SetDifference(struct Array *arr1, struct Array *arr2)
{
int i, j, k;
i=j=k=0;
struct Array *arr3 = (struct Array *)malloc(sizeof(struct Array));
while(i<arr1->length && j<arr2->length)
{
if(arr1->A[i]<arr2->A[j])
{
arr3->A[k++] = arr1->A[i++];
}
else if(arr2->A[j]<arr1->A[i])
{
j++;
}
else
{
i++;
j++;
}
}
for(;i<arr1->length; i++)
{
arr3->A[k++] = arr1->A[i];
}
arr3->length = k;
arr3->size = 10;
return arr3;
return arr3;
}
int main()
{
int delreturn;
//Creating the object of struct Array
//struct Array arr = {{2,3,4,5,6}, 10, 5};
//n-> # elements inserted;
//int n, i;
// Getting user input for Array size
//printf("Enter size of an array: ");
//scanf("%d", &arr.size);
//FYI: malloc is in <stdlib.h>
//creating the array in heap with the struct 'arr' object
//arr.A = (int *) malloc(arr.size*sizeof(int));
//setting arr.length to zero because no elements
//arr.length = 0;
//printf("Enter the number of numbers: ");
//scanf("%d", &n);
//printf("Enter the all elements: ");
//for(i=0; i<n; i++)
//{
// scanf("%d", &arr.A[i]);
//}
//Setting arr.length to n
//arr.length = n;
//Creating the object of struct Array
struct Array arr = {{2, 4, 6}, 10, 3};
struct Array arr2 = {{2, 3, 6, 7, 9}, 10, 5};
//Append(&arr, 10);
//Insert(&arr, 4, 12);
//delreturn = Delete(&arr, 1);
//printf("Deleted element: %d\n", delreturn);
//printf("Linear Search result index: %d\n", LinearSearch(arr, 12));
//printf("Linear Search-transposition result index: %d\n", LinearSearch_transposition(&arr, 12));
//printf("Linear Search-transposition result index: %d\n", LinearSearch_transposition(&arr, 12));
//printf("Linear Search-move to head result index: %d\n", LinearSearch_movetohead(&arr, 10));
//printf("Binary Searchresult index: %d\n", BinarySearch(arr, 4));
printf("Recursive Binary Searchresult index: %d\n", RecurciveBinarySearch(arr.A, 0, arr.length, 5));
printf("Get: %d\n", Get(arr, 3));
//Set(&arr, 0, 9);
printf("Max: %d\n", Max(arr));
printf("Min: %d\n", Min(arr));
printf("Sum: %d\n", Sum(arr));
printf("Avg: %f\n", Avg(arr));
DisplayArrayElements(arr);
//LeftShift_Reverse(&arr);
//DisplayArrayElements(arr);
//LeftShift_Reverse2(&arr);
//DisplayArrayElements(arr);
//To print the boolean result
//printf("Recursive Binary Searchresult index: %s", isSorted(&arr, arr.length)?"true":"false");
//insertsort(&arr, 8);
//rearrange_posandneg(&arr);
struct Array *arr3;
//arr3 = MergeArrays(&arr, &arr2);
//arr3 = SetUnion(&arr, &arr2);
//arr3 = SetIntersection(&arr, &arr2);
arr3 = SetDifference(&arr, &arr2);
DisplayArrayElements(*arr3);
return 0;
}
|
C | #include "9cc.h"
// プロトタイプ宣言
Map *new_map();
void *map_get(Map *map, char *key);
// この辺はテストコード
int expect(int line, int expected, int actual){
if(expected == actual)
return 0;
fprintf(stderr, "%d: %d expected, but got %d\n", line, expected, actual);
exit(1);
}
void test_vector(){
Vector *vec = new_vector();
expect(__LINE__, 0, vec->len);
for(int i = 0; i < 100; i++)
vec_push(vec, (void *)i);
expect(__LINE__, 100, vec->len);
expect(__LINE__, 0, (int)vec->data[0]);
expect(__LINE__, 50, (int)vec->data[50]);
expect(__LINE__, 99, (int)vec->data[99]);
printf("test_vector_ok!!\n");
}
void test_map(){
Map *map = new_map();
expect(__LINE__, 0, (int)map_get(map, "foo"));
map_put(map, "foo", (void *)2);
expect(__LINE__, 2, (int)map_get(map, "foo"));
map_put(map, "bar", (void *)4);
expect(__LINE__, 4, (int)map_get(map, "bar"));
map_put(map, "foo", (void *)6);
expect(__LINE__, 6, (int)map_get(map, "foo"));
printf("test_map_ok!!\n");
}
void runtest(){
test_vector();
test_map();
}
// Vector系のコード
Vector *new_vector(){
Vector *vec = malloc(sizeof(Vector));
vec->data = malloc(sizeof(void *) * 16);
vec->capacity = 16;
vec->len = 0;
return vec;
}
void vec_push(Vector * vec, void *elem){
if(vec->capacity == vec->len){
vec->capacity *= 2;
vec->data = realloc(vec->data, sizeof(void *) * vec->capacity);
}
vec->data[vec->len++] = elem;
}
// この辺はMap系のコード
Map *new_map(){
Map *map = malloc(sizeof(Map));
map->keys = new_vector();
map->vals = new_vector();
return map;
}
void map_put(Map *map, char *key, void *val){
vec_push(map->keys, key);
vec_push(map->vals, val);
}
void *map_get(Map *map, char *key){
for(int i = map->keys->len -1; i >= 0; i--)
if(strcmp(map->keys->data[i], key) == 0)
return map->vals->data[i];
return NULL;
}
// この辺はノード系のコード
Node *new_node(int ty, Node *lhs, Node *rhs){
Node *node = malloc(sizeof(Node));
node->ty = ty;
node->lhs = lhs;
node->rhs = rhs;
return node;
}
Node *new_node_num(int val){
Node *node = malloc(sizeof(Node));
node->ty = ND_NUM;
node->val = val;
return node;
}
|
C | #include <stdio.h>
/*
16. Faça uma função chamada DesenhaLinha. Ele deve desenhar uma linha na tela usando
vários símbolos de igual (Ex: ========). A função recebe por parâmetro quantos sinais
de igual serão mostrados.
*/
int DesenhaLinha(int n);
int main(){
int n;
printf("Insira N: ");
scanf("%d", &n);
DesenhaLinha(n);
return 0;
}
int DesenhaLinha(int n){
int i=0;
for(i=0; i<n; i++){
printf("=");
}
printf("\n");
return 0;
} |
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef float* vec3_t ;
typedef float byte ;
/* Variables and functions */
int /*<<< orphan*/ VectorScale (float const*,float,float*) ;
float lightmapCompensate ;
float lightmapGamma ;
float pow (float,float) ;
void ColorToBytes( const float *color, byte *colorBytes, float scale ){
int i;
float max, gamma;
vec3_t sample;
/* ydnar: scaling necessary for simulating r_overbrightBits on external lightmaps */
if ( scale <= 0.0f ) {
scale = 1.0f;
}
/* make a local copy */
VectorScale( color, scale, sample );
/* muck with it */
gamma = 1.0f / lightmapGamma;
for ( i = 0; i < 3; i++ )
{
/* handle negative light */
if ( sample[ i ] < 0.0f ) {
sample[ i ] = 0.0f;
continue;
}
/* gamma */
sample[ i ] = pow( sample[ i ] / 255.0f, gamma ) * 255.0f;
}
/* clamp with color normalization */
max = sample[ 0 ];
if ( sample[ 1 ] > max ) {
max = sample[ 1 ];
}
if ( sample[ 2 ] > max ) {
max = sample[ 2 ];
}
if ( max > 255.0f ) {
VectorScale( sample, ( 255.0f / max ), sample );
}
/* compensate for ingame overbrighting/bitshifting */
VectorScale( sample, ( 1.0f / lightmapCompensate ), sample );
/* store it off */
colorBytes[ 0 ] = sample[ 0 ];
colorBytes[ 1 ] = sample[ 1 ];
colorBytes[ 2 ] = sample[ 2 ];
} |
C | #include<stdio.h>
#include<stdlib.h>
int main()
{
long signed int n,d;
scanf("%ld",&n);
scanf("%ld",&d);
long signed int arr[n];
for(long signed int i=0;i<n;i++)
{
scanf("%ld",&arr[i]);
}
while(d>0){
int temp=arr[0];
for(int i=1;i<n;i++)
{
arr[i-1]=arr[i];
}
arr[n-1]=temp;
d--;
}
for(long signed int i=0;i<n;i++)
{
printf("%ld ",arr[i]);
}
}
|
C |
/*#include <stdio.h>
int main(void)
{
int radius = 7;
float pi = 3.14;
printf("The area of circle is %f", pi*radius*radius);
int height = 10;
printf("Volume of a cyliner is %f", pi*radius*radius*height);
return 0;
}*/
#include <stdio.h>
int main()
{
int a = 52, b, c;
printf("The value of a is %d", a);
return 0;
}
|
C | #include "libft.h"
#include <stdio.h> //////////
int main()
{
int result_flg = 1;
// for (int i = -2147483648; i < -2147483627; i++)
// for (int i = 2147483638; i < 2147483647; i++)
for (int i = -10; i < 100; i++)
{
printf("%d : %s , issame:%d\n", i, ft_itoa(i), (i == atoi(ft_itoa(i))) ? 1 : 0);
if (result_flg && (i != atoi(ft_itoa(i))))
result_flg = 0;
}
if (result_flg)
printf("SUCCESS!\n");
else
printf("fail...............\n");
return 0;
} |
C | #pragma once
#include "math.h"
#include "ImageBlockLocalization\ImageParser.h"
#define M_PI 3.14159265358979323846
//return value is reported by degree.
bool CalclateRotation(FPOINT* pArrayPoints, double& dwRotation)
{
double dw_xUL = pArrayPoints[0].x;
double dw_yUL = pArrayPoints[0].y;
double dw_xUR = pArrayPoints[1].x;
double dw_yUR = pArrayPoints[1].y;
//None used.
//double dw_xCenter = pArrayPoints[2].x;
//double dw_yCenter = pArrayPoints[2].y;
double dw_xLL = pArrayPoints[3].x;
double dw_yLL = pArrayPoints[3].y;
double dw_xLR = pArrayPoints[4].x;
double dw_yLR = pArrayPoints[4].y;
if((dw_xUR - dw_xUL) < 0.000001)
return false;
if((dw_xLR - dw_xLL) < 0.000001)
return false;
if((dw_yLR - dw_yUR)< 0.000001)
return false;
if((dw_yLL - dw_yUL)< 0.000001)
return false;
double dw_Rotation_Up = atan((dw_yUL - dw_yUR) / (dw_xUR - dw_xUL));
double dw_Rotation_Low = atan((dw_yLL - dw_yLR) / (dw_xLR - dw_xLL));
double dw_Rotation_Right = atan((dw_xLR - dw_xUR) / (dw_yLR - dw_yUR));
double dw_Rotation_Left = atan((dw_xLL - dw_xUL) / (dw_yLL - dw_yUL));
dwRotation = (dw_Rotation_Up + dw_Rotation_Low + dw_Rotation_Right + dw_Rotation_Left)* 180 /(4 * M_PI);
return true;
}
//return value is reported by degree.
bool CalclateTilt(FPOINT* pArrayPoints,
const double dw_Ideal_X_Center ,const double dw_Ideal_Y_Center,
const double dw_Chart_Width, const double dw_Chart_Height,
const double dw_Distance,
double& dwTiltX, double& dwTiltY)
{
if (dw_Chart_Width < 0.000001)
return false;
if (dw_Chart_Height < 0.000001)
return false;
if (dw_Distance < 0.000001)
return false;
double dw_xUL = pArrayPoints[0].x;
double dw_yUL = pArrayPoints[0].y;
double dw_xUR = pArrayPoints[1].x;
double dw_yUR = pArrayPoints[1].y;
double dw_xCenter = pArrayPoints[2].x;
double dw_yCenter = pArrayPoints[2].y;
double dw_xLL = pArrayPoints[3].x;
double dw_yLL = pArrayPoints[3].y;
double dw_xLR = pArrayPoints[4].x;
double dw_yLR = pArrayPoints[4].y;
double dw_xOffset = (dw_Ideal_X_Center - dw_xCenter);
double dw_yOffset = (dw_Ideal_Y_Center - dw_yCenter);
double dw_xUp = dw_xUL - dw_xUR;
double dw_yUp = dw_yUL - dw_yUR;
double MPlumUp = sqrt(dw_xUp*dw_xUp + dw_yUp*dw_yUp)/dw_Chart_Width;
double dw_xLow = dw_xLL - dw_xLR;
double dw_yLow = dw_yLL - dw_yLR;
double MPlumLow = sqrt(dw_xLow*dw_xLow + dw_yLow*dw_yLow)/dw_Chart_Width;
double dw_xRight = dw_xUR - dw_xLR;
double dw_yRight = dw_yUR - dw_yLR;
double MPlumRight = sqrt(dw_xRight*dw_xRight + dw_yRight*dw_yRight)/dw_Chart_Height;
double dw_xLeft = dw_xUL - dw_xLL;
double dw_yLeft = dw_yUL - dw_yLL;
double MPlumLeft = sqrt(dw_xLeft*dw_xLeft + dw_yLeft*dw_yLeft)/dw_Chart_Height;
double MPlumAvg = (MPlumUp + MPlumLow + MPlumRight + MPlumLeft) / 4;
if (MPlumAvg < 0.000001)
return false;
dwTiltX = asin( dw_xOffset / dw_Distance / MPlumAvg) * 180 / M_PI;
dwTiltY = asin( dw_yOffset / dw_Distance / MPlumAvg) * 180 / M_PI;
return true;
} |
C | #include <stdio.h>
#include <stdlib.h>
struct Node {
int val;
struct Node *back;
};
struct Node *top=NULL;
void push(int val){
struct Node* newData = (struct Node*)malloc(sizeof(struct Node));
newData->val=val;
newData->back = NULL;
if(top==NULL){
top=newData;
}else{
newData->back=top;
top=newData;
}
}
void createStack() {
char ch='N';
do {
printf("Enter value to be inserted in list\n" );
int val=0;
scanf("%d",&val);
push(val);
printf("Do you want to enter new data\n");
scanf("%c",&ch );
scanf("%c",&ch);
} while(ch=='Y'||ch=='y');
}
void pop(){
struct Node* nodeToBeDeleted = top;
if(top!=NULL){
top=top->back;
printf("%d value deleted\n",nodeToBeDeleted->val );
nodeToBeDeleted->back=NULL;
}else{
printf("Stack is empty\n");
}
}
void display(){
struct Node* start = top;
if(top!=NULL){
while(start!=NULL){
printf("%d<-",start->val);
start=start->back;
}
printf("END\n" );
}else{
printf("List is empty\n");
}
}
int main(){
createStack();
display();
printf("do you want to pop\n" );
char choice;
scanf("%c",&choice );
scanf("%c",&choice);
if(choice=='y'){
pop();
display();
}
}
|
C | #include<stdio.h>
#include<conio.h>
#include<math.h>
int stack[20],top=-1;
void push(int x)
{
stack[++top]=x;
}
int pop()
{
return(stack[top--]);
}
void main()
{
char s[20];
int x,i,y;
clrscr();
printf("\n evelation of post fix exp\n");
printf("\n enter a postfix expression");
gets(s);
for(i=0;i<strlen(s);i++)
{
if(isdigit(s[i]))
push(s[i]-'0');
else
{
y=pop();
x=pop();
switch(s[i])
{
case'+':push(x+y);
break;
case'-':push(x+y);
break;
case'*':push(x*y);
break;
case'/':push(x/y);
break;
case'^':
case'$':push(pow(x,y));
break;
}
}
}
printf("\n resulr is: %d",pop());
getch();
} |
C | #include "blocodememoria.h"
#include "endereco.h"
#include <time.h>
blocoMemoria **criaMemoriaRAM(){
blocoMemoria **bloco = malloc(tamanhoRam * sizeof(blocoMemoria));
for (int i = 0; i < tamanhoRam; i++){
bloco[i] = criablocoMemoriaRAM();
bloco[i]->end = criaEndereco(i, 0);
}
return bloco;
}
blocoMemoria **criaMemoriaCache(int tamanho){
blocoMemoria **bloco = (blocoMemoria**) malloc(tamanho * sizeof(blocoMemoria*));
for (int i = 0; i < tamanho; i++){
bloco[i] = criablocoMemoriaCache();
bloco[i]->end = criaEndereco(-1, 0);
}
return bloco;
}
blocoMemoria *criablocoMemoriaCache(){
blocoMemoria *bloco = (blocoMemoria*)malloc(sizeof(blocoMemoria));
srand(time(NULL));
for(int i = 0; i < 4; i++){
bloco->palavra[i] = rand() % 100;
}
bloco->atualizado = false;
time_t t = time(NULL);
bloco->tempo = time(&t);
return bloco;
}
//funcao para preencher um arquivo binario que sera lido pelo hd
//nao sei onde vou colocar isso nao
void preencheHD(int tamanho){
FILE *hd = fopen("HD.bin", "wb");
int palavra;
if(hd == NULL) printf("ERRO AO ABRIR O AQUIVO.\n");
for (int i = 0; i < tamanho; i++){
palavra = rand()%1000;
fwrite(&palavra, sizeof(int), 1, hd);
}
fclose(hd);
}
void limpaBlocoMemoria(blocoMemoria *bloco){
bloco->end->endBloco = -1;
time_t t = time(NULL);
bloco->tempo = time(&t);
bloco->atualizado = false;
}
blocoMemoria *criablocoMemoriaRAM(){
blocoMemoria *bloco = malloc(sizeof(blocoMemoria));
srand(time(NULL));
for(int i = 0; i < 4; i++){
bloco->palavra[i] = rand() % 100;
}
bloco->atualizado = false;
time_t t = time(NULL);
bloco->tempo = time(&t);
return bloco;
}
void liberaMemoria(blocoMemoria **cache1, blocoMemoria **cache2, blocoMemoria **cache3, blocoMemoria **Ram, double *tempo){
free(cache1);
cache1 = NULL;
free(cache2);
cache2 = NULL;
free(cache3);
cache3 = NULL;
free(tempo);
tempo = NULL;
}
blocoMemoria *getBloco (blocoMemoria **bloco, int posicao){
return bloco[posicao];
}
void setBloco(blocoMemoria **bloco, blocoMemoria *novo, int posicao){
bloco[posicao] = novo;
}
int getPalavra(blocoMemoria *bloco, int posicao){
return bloco->palavra[posicao];
}
void setPalavra(blocoMemoria *bloco, int palavra, int posicao){
bloco->palavra[posicao] = palavra;
setAtualizado(bloco);
}
int getEnderecoBloco(blocoMemoria *bloco){
return bloco->end->endBloco;
}
void setEnderecoBloco(blocoMemoria *bloco, int endereco){
bloco->end->endBloco = endereco;
}
long int getCusto(long int *vetor, int posicao){
return vetor[posicao];
}
void setCusto(long int *vetor, int posicao, int custo){
vetor[posicao]+= custo;
}
bool isAtualizado(blocoMemoria* bloco){
return bloco->atualizado;
}
void setAtualizado(blocoMemoria* bloco){
bloco->atualizado = true;
}
void setDesatualizado(blocoMemoria* bloco){
bloco->atualizado = false;
}
long int getHit(long int *vetor, int posicao){
return vetor[posicao];
}
long int getMiss(long int *vetor, int posicao){
return vetor[posicao];
}
void setHit(long int *vetor, int posicao){
vetor[posicao]+=1;
}
void setMiss(long int *vetor, int posicao){
vetor[posicao]+=1;
}
time_t getTempo(blocoMemoria *bloco){
return bloco->tempo;
}
void setTempo(blocoMemoria *bloco, time_t tempo){
bloco->tempo = tempo;
} |
C | /**
* \file login_server.c
* \fn int login(void)
* \brief Función de logueo al servidor
* \author Pose, Fernando Ezequiel. ([email protected])
* \date 2015.05.06
* \return Retorna el socket si se conecto o errores.
* \version 1.1.1
*/
//--------------
//-- Includes --
//--------------
#include "servidor.h"
int login(void){
int listener;
int on = 1;
struct sockaddr_in datosServer;
struct datos configuracion;
//Cargo ip y puerto en las variables.
if(datos_server(&configuracion) == -1){
perror("Error al abrir el archivo config");
return(-1);
}
//Creo el socket que escucha las conexiones.
listener = socket(AF_INET,SOCK_STREAM,0);
if(listener == -1){
perror("listen");
return(-1);
}
/* Si el servidor se cierra bruscamente queda ocupado el puerto
y se debe reiniciar el servidor, con setsockp se soluciona */
if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,&on, sizeof(int)) == -1){
perror("setsockopt");
return(-1);
}
//Lleno la estructura con la información del servidor.
printf("Datos del server\nip:\"%s\"\npuerto:\"%d\"\n",configuracion.ip, configuracion.puerto);
datosServer.sin_family = AF_INET;
datosServer.sin_addr.s_addr = htonl(INADDR_ANY);
datosServer.sin_port = htons(configuracion.puerto);
memset(datosServer.sin_zero,0,8);
/* Enlazo el socket a la ip:puerto contenida en la
estructura datosServer. */
if(bind(listener, (struct sockaddr*) &datosServer, sizeof datosServer) == -1){
perror("bind");
return(-1);
}
printf("Servidor conectado exitosamente\n\n");
return (listener);
}
|
C | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/common/byte_buf.h>
#include <aws/common/byte_order.h>
#include <aws/common/common.h>
#include <string.h>
/**
* Stub for aws_byte_buf_write.
* Has the same behaviour as the actual function except it doesn't actually write the bytes.
* In order to use this function safely, the user must check that the byte_buf bytes are not actually
* used by the function under test.
* TODO: Once CBMC supports proper havocing, should havoc the bytes to get full soundness.
*
* On success, returns true and updates the buffer length accordingly.
* If there is insufficient space in the buffer, returns false, leaving the
* buffer unchanged.
*/
bool aws_byte_buf_write(struct aws_byte_buf *AWS_RESTRICT buf, const uint8_t *AWS_RESTRICT src, size_t len) {
AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
AWS_PRECONDITION(AWS_MEM_IS_WRITABLE(src, len), "Input array [src] must be readable up to [len] bytes.");
if (buf->len > (SIZE_MAX >> 1) || len > (SIZE_MAX >> 1) || buf->len + len > buf->capacity) {
AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
return false;
}
/* memcpy(buf->buffer + buf->len, src, len); */
buf->len += len;
AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
return true;
}
|
C | /* -----------------------------------------------------------------------
* Demonstration of how to write unit tests for dominion-base
* Include the following lines in your makefile:
*
* testUpdateCoins: testUpdateCoins.c dominion.o rngs.o
* gcc -o testUpdateCoins -g testUpdateCoins.c dominion.o rngs.o $(CFLAGS)
* -----------------------------------------------------------------------
*/
#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "rngs.h"
int main() {
int i;
int seed = 1000;
int numPlayer = 2;
int maxBonus = 10;
int p, r, handCount;
int bonus;
int k[10] = {adventurer, council_room, feast, gardens, mine
, remodel, smithy, village, baron, great_hall};
struct gameState G;
int maxHandCount = 5;
// arrays of all coppers, silvers, and golds
int coppers[MAX_HAND];
int silvers[MAX_HAND];
int golds[MAX_HAND];
for (i = 0; i < MAX_HAND; i++)
{
coppers[i] = copper;
silvers[i] = silver;
golds[i] = gold;
}
printf ("TESTING isGameOver():\n");
numPlayer = 2;
printf("test 1 with 1 province left\n");
memset(&G, 23, sizeof(struct gameState)); // clear the game state
r = initializeGame(numPlayer, k, seed, &G); // initialize a new game
// set the number of cards on hand
G.supplyCount[province] = 1;
if (!isGameOver(&G))
printf("test passed, the game is not over\n");
else
printf("test failed, the game is over\n");
printf("test 2 with 0 provinces left\n");
G.supplyCount[province] = 0;
if (isGameOver(&G))
printf("test passed, the game is over\n");
else
printf("test failed, the game is not over\n");
printf("test 3 with 0 duchy and 0 copper\n");
G.supplyCount[province] = 1;
G.supplyCount[duchy] = 0;
G.supplyCount[copper] = 0;
if (!isGameOver(&G))
printf("test passed, the game is not over\n");
else
printf("test failed, the game is over\n");
printf("test 4 with 0 duchy, 0 copper, and 0 estate\n");
G.supplyCount[province] = 1;
G.supplyCount[duchy] = 0;
G.supplyCount[copper] = 0;
G.supplyCount[estate] = 0;
if (isGameOver(&G))
printf("test passed, the game is over\n");
else
printf("test failed, the game is not over\n");
printf("test 5 with 0 smithy\n");
G.supplyCount[duchy] = 1;
G.supplyCount[copper] = 1;
G.supplyCount[estate] = 1;
G.supplyCount[smithy] = 0;
if (!isGameOver(&G))
printf("test passed, the game is not over\n");
else
printf("test failed, the game is over\n");
printf("All tests taken!\n");
return 0;
}
|
C | /*
* @lc app=leetcode.cn id=9 lang=c
*
* [9] 回文数
*/
#include <stdlib.h>
// @lc code=start
#define TURE 1
#define FALSE 0
/*
step1: 转换为字符串;
step2: 将字符从左到右倒转;
step3: 对比倒转后是否相等;
*/
bool isPalindrome(int x){
char str[64] = {0};
int i = 0;
int numOfchar = 0;
if(x < 0){
return FALSE;
} else if ((!(x % 10)) && (x != 0)){
return FALSE;
}
/*step1: 转换为字符串;*/
while(x != 0){
str[numOfchar] = '0' + x % 10;
x /= 10;
numOfchar++;
}
str[numOfchar] = '\0';
/*step2: 判断是否为回文*/
while(str[i] != '\0'){
if(str[i++] != str[--numOfchar]){
return FALSE;
}
}
return TURE;
}
// @lc code=end
|
C | #include"header.h"
int main(void)
{
char *ptr = NULL;
int choice;
int num;
int res1;
unsigned int snum;
unsigned int dnum;
int src_pos;
int des_pos;
int pos;
int no_of_bit;
if(NULL == (ptr = (char*)malloc(sizeof(char)))){
perror("buffer is full");
exit(EXIT_FAILURE);
}
while(1){
printf("1.program to swap source and detination bit in number\n");
printf("2.program to swap specified bit between numbers\n");
printf("3.To copy the bit from snum to dnum\n");
printf("4.To toggle even or odd bits\n");
printf("5.To test and set a bit position in a number\n");
printf("6.To rotate left or right\n");
printf("7.To count bit set and bit clear\n");
printf("8.To count leading or trailing set bit\n");
printf("9.macro using bitwise operation \n");
printf("10.To set a bit\n");
printf("11.program to invert bit\n");
printf("12.program to getbit left adjusted\n"
"13.exit\n");
printf("enter the choice\n");
choice = my_atoi(readinput(ptr));
validateInt(choice);
switch(choice){
case 1:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the source\n");
snum = my_atoi(readinput(ptr));
validateInt(snum);
printf("enter the destination\n");
dnum = my_atoi(readinput(ptr));
validateInt(dnum);
printf("number to be swapped:");
dec_to_bin(num);
res1 = bit_swap(num,snum,dnum);
printf("swapped bit:");
dec_to_bin(res1);
break;
case 2:
printf("enter the first number\n");
snum = my_atoi(readinput(ptr));
validateInt(snum);
printf("enter the second number\n");
dnum = my_atoi(readinput(ptr));
validateInt(dnum);
printf("enter source position\n");
src_pos = my_atoi(readinput(ptr));
validateInt(src_pos);
printf("enter destination position\n");
des_pos = my_atoi(readinput(ptr));
validateInt(des_pos);
printf("source number :");
dec_to_bin(snum);
printf("destination number:");
dec_to_bin(dnum);
swap_bit(snum,dnum,src_pos,des_pos);
break;
case 3:
printf("enter source number\n");
snum = my_atoi(readinput(ptr));
validateInt(snum);
printf("enter destination number\n");
dnum = my_atoi(readinput(ptr));
validateInt(dnum);
printf("enter the number of bits\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the src_pos\n");
src_pos = my_atoi(readinput(ptr));
validateInt(src_pos);
printf("enter the des_pos\n");
des_pos = my_atoi(readinput(ptr));
validateInt(des_pos);
printf("source number:");
dec_to_bin(snum);
printf("destination number \n");
dec_to_bin(dnum);
res1 = bit_copy(snum,dnum,num,src_pos,des_pos);
printf("after bitcopy\n");
printf("source number:");
dec_to_bin(snum);
printf("destination number \n");
dec_to_bin(res1);
break;
case 4: printf("1.even_bit_toggle\n");
printf("2.odd_bit_toggle\n");
printf("enter your choice\n");
choice = my_atoi(readinput(ptr));
validateInt(choice);
switch(choice){
case 1:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = even_bit_toggle(num);
printf("before toggle: ");
dec_to_bin(num);
printf("after toggle: ");
dec_to_bin(res1);
break;
case 2:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = odd_bit_toggle(num);
printf("before toggle:");
dec_to_bin(num);
printf("after toggle:");
dec_to_bin(res1);
break;
default:printf("invalid input\n");
}
break;
case 5:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the position to be tested\n");
pos = my_atoi(readinput(ptr));
validateInt(pos);
printf("before setting a bit :");
dec_to_bin(num);
res1 = BIT_TS(num,pos);
printf("after setting a bit :");
dec_to_bin(res1);
break;
case 6:
printf("1.rotate bits to left\n");
printf("2.rotate bits to right\n");
printf("3.rotate bits to left by n bits.\n");
printf("4.rotate bits to right by n bits\n");
printf("enter your choice\n");
choice = my_atoi(readinput(ptr));
validateInt(choice);
switch(choice){
case 1:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("before left rotating:");
dec_to_bin(num);
res1 = left_rotate_bits(num);
printf("after left rotating:");
dec_to_bin(res1);
break;
case 2:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("before right rotating:");
dec_to_bin(num);
res1 = right_rotate_bits(num);
printf("after right rotating:");
dec_to_bin(res1);
break;
case 3:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the number of bits to be rotated\n");
pos = my_atoi(readinput(ptr));
validateInt(pos);
printf("before left rotatin:");
dec_to_bin(num);
res1 = left_rotate_n_bits(num,pos);
printf("after left rotating:");
dec_to_bin(res1);
break;
case 4:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the number of bits to be rotated\n");
pos = my_atoi(readinput(ptr));
validateInt(pos);
printf("before right rotating:");
dec_to_bin(num);
res1 = right_rotate_n_bits(num,pos);
printf("after right rotating:");
dec_to_bin(res1);
break;
default :printf("invalid input\n");
}
break;
case 7:
printf("1.to count bit set\n");
printf("2.to count bit clear\n");
printf("enter your choice\n");
choice = my_atoi(readinput(ptr));
validateInt(choice);
switch(choice){
case 1:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = count_bit_set(num);
printf("count of bitset = %d\n",res1);
break;
case 2:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = count_bit_clear(num);
printf("count of bitclear = %d\n",res1);
break;
default: printf("invalid input\n");
}
break;
case 8:
printf("1.To count the number of leading set bit.\n");
printf("2.To count the number of leading clear bit.\n");
printf("3.To count the number of trailing cleared bit.\n");
printf("4.To count number of trailing set bit.\n");
printf("Enter your choice\n");
choice = my_atoi(readinput(ptr));
validateInt(choice);
switch(choice){
case 1:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = cnt_leading_set_bits(num);
printf("number of leading set bit = %d\n",res1);
break;
case 2:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = cnt_leading_cleared_bits(num);
printf("number of leading cleared bit = %d\n",res1);
break;
case 3:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = cnt_trailing_cleared_bits(num);
printf("number of trailing cleared bit = %d\n",res1);
break;
case 4:
printf("enter a number\n");
num = my_atoi(readinput(ptr));
validateInt(num);
res1 = cnt_trailing_set_bits(num);
printf("number of trailing set bit = %d\n",res1);
break;
default:printf("invalid input\n");
}
break;
case 9:
printf("1.To find maximum and minimum of two number\n");
printf("2.To clear rightmost setbit in a number\n");
printf("3.To clear leftmost setbit in a number\n");
printf("4.To set rightmost cleared bit in a number\n");
printf("5.To set leftmost cleared bit in a number\n");
printf("6.To set bit from position 's' to 'd' in a number\n");
printf("7.To clear bit from position 's' to 'd' in a number\n");
printf("8.To toggle bit from position 's' to 'd' in a number\n");
printf("enter the choice \n");
choice = my_atoi(readinput(ptr));
validateInt(choice);
switch(choice){
case 1:
printf("enter the input1\n");
snum = my_atoi(readinput(ptr));
validateInt(snum);
printf("enter the input2\n");
dnum = my_atoi(readinput(ptr));
validateInt(dnum);
res1 = snum - dnum;
printf("maximum number is = %d \n",MAXIMUM(res1,snum,dnum));
printf("minimum number is = %d \n", MINIMUM(res1,snum,dnum));
break;
case 2:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("before rightmost setbit\n");
dec_to_bin(num);
res1 = CLEAR_RIGHTMOST_SETBIT(num);
printf("cleared rightmost setbit:");
dec_to_bin(res1);
break;
case 3:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(choice);
printf("before leftmost setbit:");
dec_to_bin(num);
res1 = CLEAR_LEFTMOST_SETBIT(num);
printf("cleared leftmost setbit:");
dec_to_bin(res1);
break;
case 4:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("before rightmost setbit:");
dec_to_bin(num);
res1 = SET_RIGHTMOST_CLEARBIT(num);
printf("after rightmost setbit:");
dec_to_bin(res1);
break;
case 5:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("befor leftmost setbit:");
dec_to_bin(num);
res1 = SET_LEFTMOST_CLEARBIT(num);
printf("after leftmost setbit");
dec_to_bin(res1);
break;
case 6:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the source position\n");
src_pos = my_atoi(readinput(ptr));
validateInt(src_pos);
printf("enter the destination position\n");
des_pos = my_atoi(readinput(ptr));
validateInt(des_pos);
printf("before set bit:");
dec_to_bin(num);
res1 = SET_BIT(num,src_pos,des_pos);
printf("after set bit:");
dec_to_bin(res1);
break;
case 7:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the source position\n");
src_pos = my_atoi(readinput(ptr));
validateInt(src_pos);
printf("enter the destination position\n");
des_pos = my_atoi(readinput(ptr));
validateInt(des_pos);
printf("before clearbit:");
dec_to_bin(num);
res1 = CLEAR_BIT(num,src_pos,des_pos);
printf("after clearbit:");
dec_to_bin(res1);
break;
case 8:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the source position\n");
src_pos = my_atoi(readinput(ptr));
validateInt(src_pos);
printf("enter the destination position\n");
des_pos = my_atoi(readinput(ptr));
validateInt(des_pos);
printf("before toggle:");
dec_to_bin(num);
res1 = TOGGLE_BIT(num,src_pos,des_pos);
printf("after toggle:");
dec_to_bin(res1);
break;
default :
printf("invalid input\n");
break;
}
break;
case 10:
printf("enter first input\n");
snum = my_atoi(readinput(ptr));
validateInt(snum);
printf("enter the second input\n");
dnum = my_atoi(readinput(ptr));
validateInt(dnum);
printf("enter the the source position\n");
src_pos = my_atoi(readinput(ptr));
validateInt(src_pos);
printf("enter the number of bits");
no_of_bit = my_atoi(readinput(ptr));
validateInt(no_of_bit);
printf("source number before setbit:");
dec_to_bin(snum);
res1 = setbit(snum,src_pos,no_of_bit,dnum);
printf("source number after setbit:");
dec_to_bin(res1);
break;
case 11:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the position\n");
pos = my_atoi(readinput(ptr));
validateInt(pos);
printf("enter the number of bits\n");
no_of_bit = my_atoi(readinput(ptr));
validateInt(no_of_bit);
printf("before inverting:");
dec_to_bin(num);
res1 = invert(num,pos,no_of_bit);
printf("after inverting:");
dec_to_bin(res1);
break;
case 12:
printf("enter the input\n");
num = my_atoi(readinput(ptr));
validateInt(num);
printf("enter the position\n");
pos = my_atoi(readinput(ptr));
validateInt(pos);
printf("enter the number of bits\n");
no_of_bit = my_atoi(readinput(ptr));
validateInt(no_of_bit);
res1 = GET_BITS(num,pos,no_of_bit);
printf("bits :");
dec_to_bin(res1);
break;
case 13: exit(EXIT_FAILURE);
default:printf("invlid input\n");
}
}
}
|
C | // Napiste prog., kt. nacita cele cislo n predstavujuce pocet vstupov. potom zo vstupu
// nacita n riadkov, kazdy obsahujuci dvojicu realnych cisiel (hodinovu mzdu a pocet hodin)
// Pre kazdu z n dvojic program vypise mzdu a nakoniec spolocnu sumu
#include <stdio.h>
double mzda (double h_mzda, double hod);
int main (){
int n, i;
double a, b, spolu = 0, m = 0;
scanf ("%d", &n);
for (i=0; i<n; i++){
scanf (" %lf %lf", &a, &b);
m = mzda (a, b);
printf ("Mzda: %lf ", m);
spolu += m;
}
printf ("\nSpolu %lf", spolu);
}
double mzda (double hod, double h_mzda){
int i;
double mzda;
for (i=0; i < hod; i++){
if (i < 40){
mzda += h_mzda;
}
if (i >= 40 && i < 60){
mzda += h_mzda * 1.5;
}
if (i >= 60){
mzda += h_mzda * 2;
}
}
return mzda;
} |
C | //
// Created by Niclas Ragnar on 2016-05-18.
//
#ifndef LOGIC_LOGIC_H
#define LOGIC_LOGIC_H
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool is_first_trick(bool played[]); // Check if it is first trick of round.
bool start_trick(char* table[], int player_pos); // Check player pos for EE on "empty"(EE,FF,FF,FF) table string.
bool do_i_start(bool played[], char **table, int player_pos); // Check if player starts.
bool play_first_trick(bool played[], char* table[], int player_pos, char player_card[], char* hand[], char lead_suit); // Play FIRST stick.
bool suit_on_hand(char* table[], char* hand[], int first_card); // Check if the player has lead suit on hand.
bool entire_hand_is_hearts(char* hand[]); // Check if player hand is only hearts.
bool only_score_cards(char* hand[]); // Check if player only have scoring cards on hand.
int find_lead_card_pos(char* []); // Find lead card position. Only run ONCE when recieving "empty" string. Return -1 on failure.
char find_lead_suit(char* table[], int first_card); // Find and return lead suit.
bool correct_suit(char played_card[], char lead_suit); // Check if played card is following suit.
bool play_trick(bool played[], char* table[],int player_pos, char played_card[], char* hand[], char lead_suit, bool broken_heart, int lead_card_pos); // Play stick.
bool discard_card(char played_card[]); // Check if discarded card is hearts.
#endif //LOGIC_LOGIC_H
|
C | #ifndef HEADER_H_ /* This is called an include guard. */
#define HEADER_H_
int h(int x); /* An int is 4 bytes! */
#endif // HEADER_H_
/*
This conditional statement will stop the compiler from processing its contents twice.
If the header is included twice, the preprocessor will skip over the content of the file, so there will be no error.
*/
|
C | #include<stdio.h>
int main(){
int Clave;
int Cont=0;
while(Clave!=23645){
printf("INGRESE LA CLAVE DE 5 DIGITOS\n\n");
scanf("%d", &Clave);
Cont++;
if(Clave!=23645){
printf("\t\t\t CLAVE INCORRECTA\n\n");
}else{
printf("\t\t\t CLAVE CORRECTA!!!!");
}
if(Cont>3){
printf("\t\t\t ADVERTENCIA!!!!");
return 0;
}
}
//printf("\n\n\t\t\t CLAVE CORRECTA!!!!!!");
}
|
C | #include<stdio.h>
void main()
{
int a;
printf("Enter the number");
scanf("%d",&a);
printf("\nNear even number::%d",a-1);
}
|
C | #include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf("enter an integer number");
scanf("%d",&n);
for(i=1;i<n;i++)
{printf("%d\t",i);
}
}
|
C | #include<stdio.h>
main() {
int a[2][4] = {1,0,3,-1,2,1,0,2};
int b[4][3] = {4,1,0,-1,1,3,2,0,1,1,3,4};
int c[2][3] = {0};
for (int i = 0;i < 2;i++) {
for (int j = 0;j < 3;j++) {
for (int k = 0;k < 4;k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
for (int i = 0;i < 2;i++) {
for (int j = 0;j < 3;j++) {
printf("%d\t", c[i][j]);
}
printf("\n");
}
} |
C | /*#include <stdio.h>
#include <stdlib.h>
int MyDijsktra(int** TheArray,int** TheShadow,int Col,int nbline,int nbcol)
{
int Max=10000;
int i,startLine;
if(Col=nbcol)
{
}
else
{
}
return 0;
}
int main()
{
int line,col,i,j;
int** TheArray;
int** TheShadow;
while(scanf("%d",&line)==1)
{
scanf("%d",&col);
TheArray=(int**)malloc(sizeof(int*)*line);
TheShadow=(int**)malloc(sizeof(int*)*line);
for(i=0;i<line;i++)
{
TheArray[i]=(int*)malloc(sizeof(int)*col);
TheShadow[i]=(int*)malloc(sizeof(int)*col);
}
for(i=0;i<line;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&TheArray[i][j]);
TheShadow[i][j]=0;
}
}
for(i=0;i<nbline;i++)
{
if(TheArray[i][Col]<Max)
{
MAx=TheArray[i][Col];
startLine=i;
}
}
}
}
*/
#include <stdio.h>
#define min(a,b) (a<b)?a:b
#define max(a,b) (a>b)?a:b
int dpath[12][102];
int dp[12][102];
int map[12][102];
int r,c;
int path(int i,int j)
{
if(j==c)
return 0;
else if(dp[i][j]!=-1)
return dp[i][j];
else
{
int m,best;
int valid[3];
valid[0]=(i+1)%r;
valid[1]=i;
valid[2]=(i+r-1)%r;
best=valid[0];
m = path(valid[0],j+1);
if(path(valid[1],j+1)<m||(path(valid[1],j+1)==m&&valid[1]<best))
{
m = path(valid[1],j+1);
best = valid[1];
}
if(path(valid[2],j+1)<m||(path(valid[2],j+1)==m&&valid[2]<best))
{
m = path(valid[2],j+1);
best = valid[2];
}
dpath[i][j]=best;
return dp[i][j]=map[i][j]+m;
}
}
int main()
{
int i,j;
while(scanf("%d %d",&r,&c)==2)
{
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
scanf("%d",map[i]+j);
dp[i][j]=-1;
}
int min = path(0,0);
int best = 0;
for(i=1;i<r;i++)
if(path(i,0)<min)
{
best = i;
min = path(i,0);
}
i = best;
for(j=0;j<c-1;j++,i = dpath[i][j])
printf("%d ",i+1);
printf("%d\n",i+1);
printf("%d\n",min);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "Talk.h"
MessageTalkList *createMessageTalkList() {
MessageTalkList *list = malloc(sizeof(MessageTalkList));
list->first = malloc(sizeof(MessageTalkCell));
list->last = list->first;
list->first->next = NULL;
return list;
}
Talk *createTalk(int talkId, int batchId) {
Talk *talk;
talk = malloc(sizeof(Talk));
talk->id = talkId;
talk->messagesSent = 0;
talk->lastBatchIdWithMessage = batchId;
talk->messageTalkList = *createMessageTalkList();
return talk;
}
void insertMessage(Message message, Talk *talk) {
TalkPointer pointer = talk->messageTalkList.first->next;
TalkPointer next;
while(pointer != NULL) {
next = pointer->next;
if(message.key < pointer->message.key) {
insertAfterPointer(message, &talk->messageTalkList, talk->messageTalkList.first);
return;
}
if(messageIsBetween(message, pointer, next)) {
insertAfterPointer(message, &talk->messageTalkList, pointer);
return;
}
pointer = pointer->next;
}
insertAfterPointer(message, &talk->messageTalkList, talk->messageTalkList.last);
}
int messageIsBetween(Message message, TalkPointer pointer, TalkPointer next) {
if(pointer == NULL || &pointer->message == NULL || next == NULL || &next->message == NULL)
return 0;
return (message.key > pointer->message.key && message.key < next->message.key);
}
void insertAfterPointer(Message message, MessageTalkList *list, TalkPointer pointer) {
TalkPointer aux = malloc(sizeof(MessageTalkCell));
aux->message = message;
aux->next = pointer->next;
if (aux->next == NULL)
list->last = aux;
pointer->next = aux;
}
Message *removeMessage(Talk *talk) {
if(talk->messageTalkList.first == NULL || talk->messageTalkList.first->next == NULL)
return NULL;
if(talk->messageTalkList.first->next->message.key != (talk->messagesSent + 1)) {
return NULL;
}
Message message = talk->messageTalkList.first->next->message;
talk->messageTalkList.first = talk->messageTalkList.first->next;
talk->messagesSent++;
return &message;
}
|
C | /*
* @file datastruct.h
* @brief Definitions and struct declarations pertaining to data
* structures
* @author John F.X. Galea
*/
#ifndef DATASTRUCT_H_
#define DATASTRUCT_H_
#include <stdint.h>
#include "dr_api.h"
/**
* @var destroy_value_function_t Safely destroys a value
*/
typedef void (*ub_destroy_value_func_t)(void *);
/**
* @var compare_func_t Comparison function to check equality between values in the list
*/
typedef bool (*ub_compare_func_t)(const void *, const void *);
/**
* @struct key_value_pair_t
*
* A pair of keys and values
*
* @var key_value_pair_t::key
* The key associated with the value
*
* @var key_value_pair_t::value
* A pointer to the value
*/
typedef struct key_value_pair {
uintptr_t key;
void *value;
} ub_key_value_pair_t;
typedef struct two_key_value_pair {
uintptr_t key1;
uintptr_t key2;
void *value;
} ub_two_key_value_pair_t;
#endif /* DATASTRUCT_H_ */
|
C | '''Leia 2 variáveis, denominadas A e B e fazer a soma dessas duas variáveis, atribuindo o resultado à variável X .
Imprima X como mostrado abaixo. Imprima a linha final após o resultado, caso contrário, você receberá " Presentation Error ".
Entrada
O arquivo de entrada conterá 2 números inteiros.
Resultado
Imprima a letra X (maiúscula) com um espaço em branco antes e depois do sinal de igual, seguido pelo valor de X,
conforme o exemplo a seguir.
Obs .: não esqueça a linha final, afinal.
'''
#include <stdio.h>
int main() {
int A=0, B=0, X=0;
scanf("%d", &A);
scanf("%d", &B);
X = A+B;
printf("X = %d", X);
printf("\n");
return 0;
}
|
C | //ѭððڵбȽϣ
//ȻСǰںһʽ
#include <stdio.h>
//Ҫֵǿ
void bubble_sort (int arr [], int sz)
{
int i = 0;
//ȷð
for ( i = 0; i < sz-1; i++)
{
int flag = 1;//贫Ѿ
//ÿһðĸ
int j = 0;
for ( j = 0; j <sz-1-i ; j++)
{
if (arr[j]>arr[j+1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = 0;
}
}
if (flag=0)
{
break;
}
}
}
int main()
{
int i = 0;
//һ
int arr[] = { 0,1,2,3,4,5,6,7,8,9 };
//ʵδβκܽдС㣻
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr,sz);
for ( i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
////ѭӡάÿԪ
//#include <stdio.h>
//
//int main()
//{
// int arr[3][4] = { { 1,2,3 },{ 4,5,6 }
// };
// int i = 0;
// for (i = 0; i < 3; i++)
// {
// int j = 0;
// for (j = 0; j < 4; j++)
// {
// printf("&arr[%d][%d]=%p \n", i, j, &arr[i][j]);
// }
// }
// return 0;
//}
////άĴ
//#include <stdio.h>
//
//int main()
//{
// int arr[3][4];//˼ʡУʡ
// int arr2[3][4] = { 1,2,3,4 };//άʼֵ
// int arr3[][4] = { { 1,2,3,4},{5,6,7,8} };
// return 0;
//}
//
////ӡеĵַ
//#include <stdio.h>
//
//int main()
//{
// int arr[] = { 1,2,3,4,5,6,7,8,9 };
// int x = sizeof(arr) / sizeof(arr[0]);
// int i = 0;
// for ( i = 0; i < x ; i++)
// {
// printf("arr[%d]=%p\n", i, &arr[i]);//ӡַҪ%p
// }
// return 0;
//}
//#include <stdio.h>
//#include <string.h>
//
//int main()
//{
// char arr1[] = "abcdef";
// int i = 0;
// for ( i = 0; i <(int)strlen(arr1); i++)
// {
// printf("%c", arr1[i]);
// }
// printf("\n");
// return 0;
//}
////strlensizeof÷
//#include <stdio.h>
//#include <string.h>
//
//int main()
//{
// char arr1[] = {'a','b','c'};
// char arr2[] = "abc";
// printf("%d\n", sizeof(arr1));//3 ַû ûб
// printf("%d\n", sizeof(arr2));//4 ַ滹\0,Ҳ
// printf("%d\n", strlen(arr1));//15 ʱ\0Ҳ\0Ըֵ
// printf("%d\n", strlen(arr2));//3
// return 0;
//}
|
C | /*
* ch14/cr8_so_many_threads.c
***************************************************************
* This program is part of the source code released for the book
* "Hands-on System Programming with Linux"
* (c) Author: Kaiwan N Billimoria
* Publisher: Packt
*
* From: Ch 14 : Multithreading Part I - The Essentials
****************************************************************
* Brief Description:
* A small program to create as many threads as the user says. The parameter is
* the number of threads to create. There must be a limit, yes?
*
* For details, please refer the book, Ch 14.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "../common.h"
void * worker(void *data)
{
long datum = (long)data;
printf("Worker thread #%5ld: pausing now...\n", datum);
(void)pause();
printf(" #%5ld: work done, exiting now\n", datum);
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
long i;
int ret;
pthread_t tid;
long numthrds=0;
if (argc != 2) {
fprintf(stderr, "Usage: %s number-of-threads-to-create\n", argv[0]);
exit(EXIT_FAILURE);
}
numthrds = atol(argv[1]);
if (numthrds <= 0) {
fprintf(stderr, "Usage: %s number-of-threads-to-create\n", argv[0]);
exit(EXIT_FAILURE);
}
for (i = 0; i < numthrds; i++) {
ret = pthread_create(&tid, NULL, worker, (void *)i);
if (ret)
FATAL("pthread_create() #%d failed! [%d]\n", i, ret);
}
pthread_exit(NULL);
}
/* vi: ts=8 */
|
C | #include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define FILENAME "bufferedio.out"
int main(int argc, char *argv[])
{
char *buffer;
FILE *fd;
int block_size, block_count;
if (argc != 3)
{
printf("usage: %s <blocksize> <blockcount>\n", argv[0]);
exit(EXIT_FAILURE);
}
fd = fopen(FILENAME, "w");
block_size = atoi(argv[1]);
block_count = atoi(argv[2]);
if ((buffer = malloc(block_size)) == NULL)
fprintf(stderr, "Error creating buffer with size %d", block_size);
for (int i = 0; i < block_count; i++)
{
fwrite(buffer, block_size, 1, fd);
}
free(buffer);
buffer = NULL;
fclose(fd);
return EXIT_SUCCESS;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split_whitespace.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hypark <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/23 16:44:43 by hypark #+# #+# */
/* Updated: 2018/05/24 16:14:05 by hypark ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
int ft_check_sep(char c)
{
return (c == ' ' || c == '\t' || c == '\n');
}
int ft_count_word(char *str)
{
int n_word;
n_word = 0;
while (*str != '\0')
{
if (ft_check_sep(*str))
str++;
else
{
n_word += 1;
str++;
while (*str != '\0' && !ft_check_sep(*str))
str++;
}
}
return (n_word);
}
void ft_fill_word(char *str, char **result, int *i)
{
int n_char;
char *cp_str;
n_char = 0;
cp_str = str;
while (*str != '\0' && !ft_check_sep(*str))
{
n_char++;
str++;
}
result[*i] = (char *)malloc(sizeof(char) * (n_char + 1));
}
void ft_fill_add(char *str, char **result, int *i, int n_word)
{
int j;
while (*str != '\0' && *i < n_word)
{
if (ft_check_sep(*str))
str++;
else
{
ft_fill_word(str, result, i);
j = 0;
while (*str != '\0' && !ft_check_sep(*str))
{
result[*i][j] = *str;
str++;
j++;
}
result[*i][j] = '\0';
*i += 1;
}
}
}
char **ft_split_whitespaces(char *str)
{
char **result;
char *cp_str;
int n_word;
int i;
i = 0;
n_word = 0;
cp_str = str;
while (*cp_str)
{
n_word += 1;
cp_str++;
}
result = (char **)malloc(sizeof(char *) * (n_word + 1));
n_word = ft_count_word(str);
ft_fill_add(str, result, &i, n_word);
result[i] = 0;
return (result);
}
|
C | #include "../include/xxhash.h"
#include "../include/isaac.h"
#include "../include/ilog.h"
#include "./filters.h"
#include "./bitutils.h"
#include "stdio.h"
#include "stdlib.h"
#define RANDOM_SEED1 123456789
#define RANDOM_SEED2 987654321
static const unsigned char *ISAAC_SEED = (unsigned char*)"22333322";
/**
* Generate k independent uniformly distributed hash values in range 0...m-1.
* For the theory, see https://www.eecs.harvard.edu/~michaelm/postscripts/rsa2008.pdf
*
* data: pointer to the data
* length: size of data to calculate hash codes (num of bytes)
* k: number of hash functions
* m: range of hash codes
* hash_codes: pointer to the result to be stored
*/
void gen_k_hash32(const void *data, int length, int k, int m, unsigned int *hash_codes)
{
unsigned int h1 = XXH32(data, length, RANDOM_SEED1);
unsigned int h2 = XXH32(data, length, RANDOM_SEED2);
for (int i=0; i<k; ++i)
{
hash_codes[i] = (h1 + i * h2) % m;
}
}
/**
* Init a standard Bloom filter.
*
* bf: pointer to a BF
* K: number of hash functions
* m: number of bits
*/
void init_bf(BF *bf, int K, int m)
{
CounterBitSet bitset;
init_counters(&bitset, m, 1);
bf->bitset = bitset;
bf->K = K;
bf->m = m;
bf->hash_codes = (unsigned int *)malloc(K * sizeof(unsigned int));
}
/**
* Insert an element to Bloom filter.
*
* bf: pointer to a BF
* data: pointer to the element to be inserted
* length: length of data (number of bytes used to calculate hash values)
*/
void insert_bf(BF *bf, void *data, int length)
{
gen_k_hash32(data, length, bf->K, bf->m, bf->hash_codes);
for (int i=0; i<bf->K; ++i)
{
set_to_max(&(bf->bitset), bf->hash_codes[i]);
}
}
/**
* Membership query processing.
*
* bf: pointer to a BF
* data: pointer to the queried element
* length: length of data (number of bytes used to calculate hash values)
*/
int test_bf(BF *bf, void *data, int length)
{
gen_k_hash32(data, length, bf->K, bf->m, bf->hash_codes);
for (int i=0; i<bf->K; ++i)
{
if (! test_counter(&(bf->bitset), bf->hash_codes[i]))
{
return 0;
}
}
return 1;
}
/**
* Release memory allocated to BF.
*
* bf: pointer to a BF
*/
void free_bf(BF *bf)
{
free_counters(&(bf->bitset));
free(bf->hash_codes);
}
/**
* Init a stable Bloom filter.
*
* sbf: pointer to an SBF
* P: number of counters to be decremented
* K: number of counters to be set
* m: number of counters
* bits_per_counter: bits used per counter
*/
void init_sbf(SBF *sbf, int P, int K, int m, int bits_per_counter)
{
CounterBitSet counters;
init_counters(&counters, m, bits_per_counter);
sbf->counters = counters;
sbf->P = P;
sbf->K = K;
sbf->m = m;
sbf->hash_codes = (unsigned int *)malloc(K * sizeof(unsigned int));
isaac_ctx isaac;
isaac_init(&isaac, ISAAC_SEED, sizeof(ISAAC_SEED));
sbf->isaac = isaac;
}
/**
* Insert an element to an SBF.
*
* sbf: pointer to an SBF
* data: pointer to element to be inserted
* length: length of data (number of bytes used to calculate hash values)
*/
void insert_sbf(SBF *sbf, void *data, int length)
{
// first decrement P counters
for (int i=0; i<sbf->P; ++i)
{
decrement(&(sbf->counters), isaac_next_uint(&(sbf->isaac), sbf->m));
}
// then set K counters to Max
gen_k_hash32(data, length, sbf->K, sbf->m, sbf->hash_codes);
for (int i=0; i<sbf->K; ++i)
{
set_to_max(&(sbf->counters), sbf->hash_codes[i]);
}
}
/**
* Membership query processing.
*
* sbf: pointer to an SBF
* data: pointer to element to be inserted
* length: length of data (number of bytes used to calculate hash values)
*/
int test_sbf(SBF *sbf, void *data, int length)
{
gen_k_hash32(data, length, sbf->K, sbf->m, sbf->hash_codes);
for (int i=0; i<sbf->K; ++i)
{
if (! test_counter(&(sbf->counters), sbf->hash_codes[i]))
{
return 0;
}
}
return 1;
}
/**
* Release memory allocated to sbf.
*
* sbf: pointer to an SBF
*/
void free_sbf(SBF *sbf)
{
free_counters(&(sbf->counters));
free(sbf->hash_codes);
}
/**
* Init a Learned Bloom filter.
*
* lbf: pointer to an LBF
* model: pointer to a Model
* K: number of hash functions used in the backup filter
* m: number of bits used in the backup filter
* tau: decision threshold of the model
*/
void init_lbf(LBF *lbf, Model *model, int K, int m, float tau)
{
BF bf;
init_bf(&bf, K, m);
lbf->bf = bf;
lbf->tau = tau;
lbf->model = *model;
}
/**
* Insert an element to the learned Bloom filter.
*
* lbf: pointer to an LBF
* data: pointer to the Data object to be inserted
* length: number of bytes to be used to calculate hash codes
*/
void insert_lbf(LBF *lbf, Data *data, int length)
{
if (predict(&(lbf->model), data) < lbf->tau)
{
insert_bf(&(lbf->bf), &(data->id), length);
}
}
/**
* Membership test query processing.
*
* lbf: pointer to an LBF
* data: pointer to the Data object to be inserted
* length: number of bytes to be used to calculate hash codes
*/
int test_lbf(LBF *lbf, Data *data, int length)
{
if (predict(&(lbf->model), data) > lbf->tau)
{
return 1;
}
else
{
return test_bf(&(lbf->bf), &(data->id), length);
}
}
/**
* Release memory allocated to lbf.
*
* lbf: pointer to an LBF
*/
void free_lbf(LBF *lbf)
{
free_bf(&(lbf->bf));
if (lbf->model.catboost_model_handle)
{
ModelCalcerDelete(lbf->model.catboost_model_handle);
}
}
/**
* Init a Single Stable Learned Bloom filter.
*
* sslbf: pointer to an SSLBF
* model: pointer to a Model
* P: number of counters to be decremented
* K: number of counters to be set
* m: number of counters
* bits_per_counter: bits used per counter
* tau: decision threshold of the model
*/
void init_sslbf(SSLBF *sslbf, Model *model, int P, int K, int m, int bits_per_counter, float tau)
{
SBF sbf;
init_sbf(&sbf, P, K, m, bits_per_counter);
sslbf->sbf = sbf;
sslbf->model = *model;
sslbf->tau = tau;
}
/**
* Insert an element to the SSLBF.
*
* sslbf: pointer to an SSLBF
* data: pointer to the Data object to be inserted
* length: number of bytes to be used to calculate hash codes
*/
void insert_sslbf(SSLBF *sslbf, Data *data, int length)
{
if (predict(&(sslbf->model), data) < sslbf->tau)
{
insert_sbf(&(sslbf->sbf), &(data->id), length);
}
}
/**
* Membership test query processing.
*
* sslbf: pointer to an SSLBF
* data: pointer to the Data object to be inserted
* length: number of bytes to be used to calculate hash codes
*/
int test_sslbf(SSLBF *sslbf, Data *data, int length)
{
if (predict(&(sslbf->model), data) > sslbf->tau)
{
return 1;
}
else
{
return test_sbf(&(sslbf->sbf), &(data->id), length);
}
}
/**
* Release memory allocated to sslbf.
*
* sslbf: pointer to an SSLBF
*/
void free_sslbf(SSLBF *sslbf)
{
ModelCalcerDelete(&(sslbf->model));
free_sbf(&(sslbf->sbf));
}
/**
* Find idx of x belonging to which interval
*/
static int lookup_interval(float *intervals, int len, float x)
{
int lo = 0, hi = len;
int idx;
while ((hi - lo) > 1)
{
idx = lo + (hi - lo) / 2;
if (x > intervals[idx])
{
lo = idx;
}
else
{
hi = idx;
}
}
return lo;
}
/**
* Init a Grouping Stable Learned Bloom filter.
*
* gslbf: pointer to an GSLBF
* model: pointer to a Model
* P_array: array of parameter P [of size g]
* K_array: array of parameter K [of size g]
* m_array: array of parameter m [of size g]
* bits_per_counter_array: array of parameter bits_per_counter [of size g]
* tau_array: array of decision thresholds [of size g+1]
* g: number of groups
*/
void init_gslbf(GSLBF *gslbf, Model *model, int *P_array, int *K_array, int *m_array, int *bits_per_counter_array, float *tau_array, int g)
{
SBF *SBF_array = (SBF *)malloc(g * sizeof(SBF));
for (int i=0; i<g; ++i)
{
SBF sbf;
init_sbf(&sbf, P_array[i], K_array[i], m_array[i], bits_per_counter_array[i]);
SBF_array[i] = sbf;
}
gslbf->SBF_array = SBF_array;
gslbf->model = *model;
gslbf->tau_array = tau_array;
gslbf->g = g;
}
/**
* Insert an element to the GSLBF.
*
* gsslbf: pointer to an GSSLBF
* data: pointer to the Data object to be inserted
* length: number of bytes to be used to calculate hash codes
*/
void insert_gslbf(GSLBF *gslbf, Data *data, int length)
{
float score = predict(&(gslbf->model), data);
int idx = lookup_interval(gslbf->tau_array, gslbf->g + 1, score);
insert_sbf(&(gslbf->SBF_array[idx]), data, length);
}
/**
* Membership test query processing.
*
* gslbf: pointer to an GSLBF
* data: pointer to the Data object to be inserted
* length: number of bytes to be used to calculate hash codes
*/
int test_gslbf(GSLBF *gslbf, Data *data, int length)
{
float score = predict(&(gslbf->model), data);
int idx = lookup_interval(gslbf->tau_array, gslbf->g + 1, score);
return test_sbf(&(gslbf->SBF_array[idx]), data, length);
}
/**
* Release memory allocated to gslbf.
*
* gslbf: pointer to an GSLBF
*/
void free_gslbf(GSLBF *gslbf)
{
ModelCalcerDelete(&(gslbf->model));
free(gslbf->SBF_array);
gslbf->SBF_array = NULL;
}
|
C | #include <pthread.h>
#include <stdio.h>
void* run_proc(void* x_void_ptr) {
printf("Hello from thread\n");
}
int main() {
printf("Creating threads\n");
pthread_t t1;
if (pthread_create(&t1, NULL, run_proc, NULL)) {
printf("Error creating the thread\n");
return 0;
}
if (pthread_join(t1, NULL)) {
printf("Error joining\n");
return 0;
}
printf("All good\n");
return 0;
}
|
C | /*
Lab Test 3 A semaphore implementation of the producer consumer problem
*/
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define BUFF_SIZE 10
char buffer[BUFF_SIZE];
int nextIn = 0;
int nextOut = 0;
sem_t empty_slots;
sem_t full_slots;
sem_t mutex;
// The producer function
void Put(char item)
{
// insert code for the P functions for the empty and mutex semaphores;
//P function for empty and mutex
sem_wait(&empty_slots);
sem_wait(&mutex);
// the critical region for the producer thread
buffer[nextIn] = item;
nextIn = (nextIn + 1) % BUFF_SIZE;
printf("Producing %c ...\n", item);
// code for the V functions of the mutex and full semaphores}
//V functions for full and mutex
sem_post(&full_slots);
sem_post(&mutex);
//The producer thread
void * Producer(void *arg)
{
int i;
// code to run the producer thread 10 times
for(i = 0; i < 10; i++)
{
Put((char)('A'+ i % 26)); // inserts a letter of the alphabeth into the bounder buffer array
}
pthread_exit( NULL );
return NULL;
}
// insert code for the consumer function
void Get()
{
if(nextIn)
// insert code for the consumer function of the consumer thread
}
/* insert code for the consumer thread: */
void * Consumer(void * arg)
int value;
/* you will need put the thread consumer thread to sleep for a briefly while
in order for the program to run "ideally" */
sem_wait(&empty_slots);
//lock mute so code cannot be altered
pthread_mutex_lock(&mutex);
value = Producer(buffer);
//unlock so code can finish
pthread_mutex_unlock(&mutex);
sem_post(&full_slots)
printf("%s\n", buffer);
pthread_exit( NULL );
return NULL;
}
int main(int argc, int **argv)
{
pthread_t idP, idC;
int rc1, rc2;
// insert code to initalise all three semaphore
sem_init( &full_slots, 0, BUFF_SIZE );
sem_init( &empty_slots, 0, 0 );//second set to 0 to assure first is executed
// create thread for producer
if( (rc1=pthread_create( &idP, NULL, Producer, NULL)) )
{
printf("Thread creation failed: %d\n", rc1);
}
//insert code to create thread for consumer
rc2 = pthread_create( &idC, NULL, Consumer, NULL);
/*insert code that prevents process from closing before threads are executed */
/* prevents process from closing before threads are executed */
pthread_join( threads[ 0 ], NULL );
pthread_join( threads[ 1 ], NULL );
// destroy all the semaphores
sem_destroy( &empty_slots);
sem_destroy( &full_slots);
sem_destroy(&mutex);
return 0;
} |
C | #include<stdio.h>;
void swap(int*b1,int* b2)
{
int a;
a = *b1;
*b1 = *b2;
*b2 = a;
}
int main()
{
int a1[5] = { 1,2,3,4,5 };
int a2[5] = { 5,4,3,2,1 };
for (int i = 0; i < 5; i++)
{
swap(&a1[i], &a2[i]);
}
for (int i = 0; i < 5; i++)
{
printf("%d ", a1[i]);
}
printf("\n");
for (int i = 0; i < 5; i++)
{
printf("%d ", a2[i]);
}
} |
C | /*-
* Copyright (c) 2013-2018 Hans Petter Selasky
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This file implements helper functions for XOR multiplication,
* division, exponent, logarithm and so on.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "math_bin.h"
/*
* ========================================================================
* BASE-2 XOR
* ========================================================================
*/
#define MBIN_XOR2_MOD_64(p) ((1ULL << (p)) + 1ULL)
#define MBIN_XOR2_BASE_64(p) 3ULL
uint64_t
mbin_xor2_rol_mod_64(uint64_t val, uint8_t shift, uint8_t p)
{
val = (val << shift) | (val >> (p - shift));
val &= (1ULL << p) - 1ULL;
return (val);
}
uint64_t
mbin_xor2_ror_mod_64(uint64_t val, uint8_t shift, uint8_t p)
{
val = (val >> shift) | (val << (p - shift));
val &= (1ULL << p) - 1ULL;
return (val);
}
uint64_t
mbin_xor2_square_mod_64(uint64_t x, uint8_t p)
{
uint64_t r = 0;
uint8_t n;
uint8_t q;
for (q = n = 0; n != p; n++) {
if (x & (1ULL << n))
r ^= 1ULL << q;
q += 2;
if (q >= p)
q -= p;
}
return (r);
}
uint64_t
mbin_xor2_multi_square_mod_64(uint64_t x, uint8_t y, uint8_t p)
{
uint64_t r = 0;
uint8_t q = 0;
do {
if (x & 1)
r ^= (1ULL << q);
q += y;
if (q >= p)
q -= p;
} while ((x /= 2));
return (r);
}
uint64_t
mbin_xor2_root_mod_64(uint64_t x, uint8_t p)
{
uint64_t r = 0;
uint8_t n;
uint8_t q;
for (q = n = 0; n != p; n++) {
if (x & (1ULL << q))
r ^= 1ULL << n;
q += 2;
if (q >= p)
q -= p;
}
return (r);
}
uint64_t
mbin_xor2_exp3_mod_64(uint64_t x, uint64_t y, uint8_t p)
{
uint8_t n;
uint8_t r;
for (r = 1, n = 0; n != p; r *= 2, n++) {
if (r >= p)
r -= p;
if (y & (1ULL << n))
x = x ^ mbin_xor2_rol_mod_64(x, r, p);
}
return (x);
}
uint64_t
mbin_xor2_crc2bin_64(uint64_t z, uint8_t p)
{
uint64_t r;
uint8_t x;
uint8_t y;
r = (z & 1);
for (y = 1, x = 1; x != p; y *= 2, x++) {
if (y >= p)
y -= p;
if (z & (1ULL << y))
r |= (1ULL << x);
}
return (r);
}
uint64_t
mbin_xor2_bin2crc_64(uint64_t z, uint8_t p)
{
uint64_t r;
uint8_t x;
uint8_t y;
r = (z & 1);
for (y = 1, x = 1; x != p; y *= 2, x++) {
if (y >= p)
y -= p;
if (z & (1ULL << x))
r |= (1ULL << y);
}
return (r);
}
void
mbin_xor2_compute_inverse_table_64(struct mbin_xor2_pair_64 src,
struct mbin_xor2_pair_64 dst, uint64_t *ptr, uint8_t lmax)
{
uint64_t table[lmax][2];
uint64_t temp[2][lmax];
uint64_t m;
uint64_t u;
uint64_t v;
uint8_t x;
uint8_t y;
for (u = v = 1, x = 0; x != lmax; x++) {
temp[0][x] = u;
temp[1][x] = v;
u = mbin_xor2_mul_mod_any_64(u, src.val, src.mod);
v = mbin_xor2_mul_mod_any_64(v, dst.val, dst.mod);
}
memset(table, 0, sizeof(table));
memset(ptr, 0, sizeof(ptr[0]) * lmax);
for (x = 0; x != lmax; x++) {
for (y = 0; y != lmax; y++) {
table[y][0] |= ((temp[0][x] >> y) & 1) << x;
table[y][1] |= ((temp[1][x] >> y) & 1) << x;
}
}
for (x = 0; x != lmax; x++) {
if (table[x][0] == 0)
continue;
m = mbin_msb64(table[x][0]);
for (y = 0; y != lmax; y++) {
if (y == x)
continue;
if (table[y][0] & m) {
table[y][0] ^= table[x][0];
table[y][1] ^= table[x][1];
}
}
}
for (x = 0; x != lmax; x++) {
if (table[x][0] == 0)
continue;
y = mbin_sumbits64(mbin_msb64(table[x][0]) - 1ULL);
ptr[y] = table[x][1];
}
}
uint64_t
mbin_xor2_compute_inverse_64(uint64_t x, const uint64_t *ptr, uint8_t lmax)
{
uint64_t r;
uint8_t y;
for (r = 0, y = 0; y != lmax; y++) {
if (mbin_sumbits64(x & ptr[y]) & 1)
r ^= (1ULL << y);
}
return (r);
}
uint64_t
mbin_xor2_compute_div_64(uint64_t rem, uint64_t div,
uint64_t mod, uint64_t *pmod)
{
uint8_t lmax = mbin_sumbits64(mbin_msb64(mod) - 1ULL);
uint64_t table[lmax];
struct mbin_xor2_pair_64 src = {div, mod};
struct mbin_xor2_pair_64 dst = {2, mod};
mbin_xor2_compute_inverse_table_64(src, dst, table, lmax);
if (pmod != NULL) {
/* compute modulus */
uint64_t temp = div;
temp = mbin_xor2_exp_mod_any_64(temp, lmax, mod);
temp = mbin_xor2_compute_inverse_64(temp, table, mod) ^
(1ULL << lmax);
*pmod = temp;
}
return (mbin_xor2_compute_inverse_64(rem, table, mod));
}
uint64_t
mbin_xor2_compute_exp_64(uint64_t base, uint64_t exp, uint64_t mod)
{
uint8_t lmax = mbin_sumbits64(mbin_msb64(mod) - 1ULL);
uint8_t value[lmax];
uint8_t a;
uint8_t x;
uint8_t y;
uint64_t func[lmax];
uint64_t table[lmax];
uint64_t m;
uint64_t u;
/*
* Compute modulus for exponent
*/
for (u = 1, x = 0; x != lmax; x++) {
func[x] = u;
u = mbin_xor2_mul_mod_any_64(u, base, mod);
}
memset(table, 0, sizeof(table));
for (x = 0; x != lmax; x++) {
for (y = 0; y != lmax; y++) {
table[y] |= ((func[x] >> y) & 1ULL) << x;
}
value[x] = (u >> x) & 1;
}
for (x = 0; x != lmax; x++) {
m = mbin_lsb64(table[x]);
for (y = 0; y != lmax; y++) {
if (y == x)
continue;
if (table[y] & m) {
table[y] ^= table[x];
value[y] ^= value[x];
}
}
}
for (u = (1ULL << lmax), x = 0; x != lmax; x++) {
if (table[x] && value[x]) {
y = mbin_sumbits64(table[x] - 1ULL);
u |= 1ULL << y;
}
}
/* compute exponent */
u = mbin_xor2_exp_mod_any_64(2, exp, u);
for (m = 0, a = 0; a != lmax; a++) {
if ((u >> a) & 1)
m ^= func[a];
}
return (m);
}
uint64_t
mbin_xor2_mul_table_64(uint64_t a, uint64_t b, const uint64_t *table,
uint64_t n)
{
uint64_t x, y, r;
r = 0;
for (x = 0; x != n; x++) {
if (!((a >> x) & 1))
continue;
for (y = 0; y != n; y++) {
if (!((b >> y) & 1))
continue;
r ^= table[x + (y * n)];
}
}
return (r);
}
int
mbin_xor2_mul_table_init_64(uint64_t n, const uint64_t *input /* 2*n */ ,
uint64_t *output /* n**2 */ )
{
const uint64_t words = ((n * n) + 63) / 64;
uint64_t bitmap[n * n][words];
uint64_t value[n * n];
uint64_t x, y, u, t, m;
memset(bitmap, 0, sizeof(bitmap));
memset(value, 0, sizeof(value));
memset(output, 0, sizeof(output[0]) * n * n);
for (x = 0; x != n; x++) {
for (y = 0; y != n; y++) {
value[x + (y * n)] = input[x + y];
for (t = 0; t != n; t++) {
for (u = 0; u != n; u++) {
if ((input[x] >> t) & (input[y] >> u) & 1) {
uint64_t off = t + (u * n);
bitmap[x + (y * n)][off / 64] |= (1ULL << (off % 64));
}
}
}
}
}
for (x = 0; x != (n * n); x++) {
for (y = 0; y != words; y++) {
if (bitmap[x][y] == 0)
continue;
m = mbin_lsb64(bitmap[x][y]);
for (u = 0; u != (n * n); u++) {
if (u == x)
continue;
if (bitmap[u][y] & m) {
for (t = 0; t != words; t++)
bitmap[u][t] ^= bitmap[x][t];
value[u] ^= value[x];
}
}
break;
}
if (y == words)
return (-1);
}
for (x = 0; x != (n * n); x++) {
for (u = y = 0; y != words; y++) {
u += mbin_sumbits64(bitmap[x][y]);
}
if (u != 1) {
return (-1);
}
for (y = 0; y != words; y++) {
if (bitmap[x][y] == 0)
continue;
m = mbin_sumbits64(mbin_lsb64(bitmap[x][y]) - 1ULL) + (y * 64);
output[m] = value[x];
break;
}
}
return (0);
}
uint64_t
mbin_xor2_step_fwd_64(uint64_t x, uint64_t mask)
{
uint64_t m = (mbin_msb64(mask) << 1) - 1ULL;
return (((x << 1) | (mbin_sumbits64(x & mask) & 1)) & m);
}
/*
* Example:
* mod=0xa41825, base=2, len=2520
*
* Properties:
* f(a,b) = f(b,a)
*/
uint64_t
mbin_xor2_multiply_plain_64(uint64_t a, uint64_t b, uint64_t mod)
{
uint8_t lmax = mbin_sumbits64(mbin_msb64(mod) - 1ULL);
uint8_t x;
uint64_t r;
uint64_t s;
for (r = 0, s = 1, x = 0; x != lmax; x++) {
if ((a >> x) & 1)
r ^= s;
s = mbin_xor2_mul_mod_any_64(s, b, mod);
}
return (r);
}
/*
* Symmetric version of function above
*/
uint64_t
mbin_xor2_mul_plain_symmetric_64(uint64_t x, uint64_t y, uint64_t mod)
{
uint64_t retval = 0;
uint8_t a;
uint8_t b;
uint8_t max;
max = mbin_sumbits64(mbin_msb64(mod) - 1);
for (a = 0; a != max; a++) {
if (((x >> a) & 1) == 0)
continue;
for (b = 0; b != max; b++) {
if (((y >> b) & 1) == 0)
continue;
retval ^=
mbin_xor2_exp_mod_any_64(2, a * b, mod);
}
}
return (retval);
}
/*
* Square function, derived from function above:
*/
uint64_t
mbin_xor2_square_plain_64(uint64_t x, uint64_t mod)
{
uint64_t retval = 0;
uint8_t a;
uint8_t max;
max = mbin_sumbits64(mbin_msb64(mod) - 1);
for (a = 0; a != max; a++) {
if ((x >> a) & 1) {
retval ^=
mbin_xor2_exp_mod_any_64(2, a * a, mod);
}
}
return (retval);
}
/*
* Negate function which works with polynoms that are mirrored.
*/
uint64_t
mbin_xor2_negate_plain_64(uint64_t x, uint64_t mod)
{
uint8_t max;
#if 0
if (mbin_xor2_is_mirror_64(mod) == 0)
return (0);
#endif
/* compute the maximum power of the polyom we are using */
max = mbin_sumbits64(mbin_msb64(mod) - 1);
/* multiply bias into result before negation */
x = mbin_xor2_mul_mod_any_64(x, (1ULL << (max - 1)), mod);
/* negation value */
x = mbin_bitrev64(x << (64 - max));
return (x);
}
/*
* Polynom generator
*/
void
mbin_xor2_generate_plain_64(uint8_t size, uint64_t *poly, uint64_t *lin_mod)
{
uint64_t x = 3;
uint64_t y = 1;
uint16_t a;
uint16_t b;
for (a = 3;; a += 2) {
/* figure out next prime */
if (a != 3) {
for (b = 3; b != a; b += 2) {
if ((a % b) == 0)
break;
}
if (b != a)
continue;
}
/* see if end */
if (!size--) {
*poly = x;
*lin_mod = y;
break;
}
/* accumulate */
x = mbin_xor2_mul_64(x, (1ULL << a) - 1ULL);
y *= a;
}
}
/* Returns zero if the polynom is reciprocal */
uint64_t
mbin_xor2_is_reciprocal_plain_64(uint64_t mod)
{
uint64_t rem = 0;
uint8_t x;
for (x = 0; x != 64; x++) {
uint64_t y;
if (!(mod & (1ULL << x)))
continue;
y = mbin_xor2_exp_mod_any_64(2, x, mod);
y = mbin_xor2_negate_plain_64(y, mod);
rem ^= y;
}
return (rem);
}
uint64_t
mbin_xor2_divide_plain_64(uint64_t rem, uint64_t div,
uint64_t mod, uint8_t *psolved)
{
uint8_t lmax = mbin_sumbits64(mbin_msb64(mod) - 1ULL);
uint8_t value[lmax];
uint8_t x;
uint8_t y;
uint64_t func[lmax];
uint64_t table[lmax];
uint64_t m;
uint64_t u;
for (u = 1, x = 0; x != lmax; x++) {
func[x] = u;
u = mbin_xor2_mul_mod_any_64(u, div, mod);
}
memset(table, 0, sizeof(table));
for (x = 0; x != lmax; x++) {
for (y = 0; y != lmax; y++) {
table[y] |= ((func[x] >> y) & 1ULL) << x;
}
value[x] = (rem >> x) & 1;
}
top:
for (x = 0; x != lmax; x++) {
m = mbin_lsb64(table[x]);
for (y = 0; y != lmax; y++) {
if (y == x)
continue;
if (table[y] & m) {
table[y] ^= table[x];
value[y] ^= value[x];
}
}
}
for (x = 0; x != lmax; x++) {
m = mbin_lsb64(table[x]);
if (table[x] != m) {
for (y = 0; y != lmax; y++) {
table[y] &= ~m;
}
goto top;
}
}
if (psolved)
*psolved = 1;
/* gather solution */
for (u = 0, x = 0; x != lmax; x++) {
if (value[x]) {
if (table[x]) {
/* store solution bit */
y = mbin_sumbits64(table[x] - 1ULL);
u |= 1ULL << y;
} else {
/* equation set has no solution */
if (psolved)
*psolved = 0;
}
}
}
return (u);
}
uint8_t
mbin_xor2_factor_fast_64(uint64_t rem, uint8_t p)
{
int16_t stats[p];
uint8_t x;
uint8_t y;
memset(stats, 0, sizeof(stats));
/* collect statistics */
for (x = 0; x != p; x++) {
if (((rem >> x) & 1) == 0)
continue;
for (y = x + 1; y != p; y++) {
stats[y - x] += 2 * ((rem >> y) & 1) - 1;
}
}
/* find most hits */
for (x = y = 1; x < p; x++) {
if ((stats[x] + stats[p - x]) > (stats[y] + stats[p - y]))
y = x;
}
return (y);
}
uint64_t
mbin_xor2_log3_mod_64(uint64_t x, uint8_t p)
{
uint64_t mask;
uint64_t d2;
uint64_t z;
uint8_t pm;
uint8_t n;
uint8_t r;
uint8_t sbx;
uint8_t ntable[p];
/* Check for NUL */
if (x <= 1)
return (0);
/* setup MOD table */
pm = (p - 1) / 2;
mask = p * ((1ULL << pm) - 1ULL);
d2 = ((1ULL << pm) - 1ULL);
/* there might be unused entries */
memset(ntable, 0, sizeof(ntable));
for (r = 1, n = 0; n != p; r *= 2, n++) {
if (r >= p)
r -= p;
ntable[r] = n;
}
z = 0;
/* Iterate until a solution is found */
while (1) {
sbx = mbin_sumbits64(x);
if (sbx >= (p - 2) || sbx <= 2)
break;
/* factor found - update */
r = mbin_xor2_factor_fast_64(x, p);
x = x ^ mbin_xor2_rol_mod_64(x, r, p);
z += (1ULL << ntable[r]);
}
if (sbx >= (p - 2))
x ^= (1ULL << p) - 1ULL;
sbx = mbin_sumbits64(x);
/* sanity check */
if (sbx == 0)
return (0);
/* shift down */
while (!(x & 1ULL)) {
z += d2;
x /= 2ULL;
}
if (sbx == 1)
return ((mask - (z % mask)) % mask);
if (sbx != 2)
return (0);
/* locate second bit */
r = mbin_sumbits64(x - 2ULL);
/* properly MOD the "z" variable */
z = (mask + (1ULL << ntable[r]) - (z % mask)) % mask;
return (z);
}
uint64_t
mbin_xor2_log3_mod_64_alt1(uint64_t x, uint8_t p)
{
uint64_t mask;
uint64_t d2;
uint64_t y;
uint64_t z;
uint8_t pm;
uint8_t n;
uint8_t r;
uint8_t sbx;
uint8_t sby;
uint8_t ntable[p];
uint8_t to = p;
/* Check for NUL */
if (x <= 1)
return (0);
/* setup MOD table */
pm = (p - 1) / 2;
mask = p * ((1ULL << pm) - 1ULL);
d2 = ((1ULL << pm) - 1ULL);
/* there might be unused entries */
memset(ntable, 0, sizeof(ntable));
for (r = 1, n = 0; n != p; r *= 2, n++) {
if (r >= p)
r -= p;
ntable[r] = n;
}
z = 0;
sbx = mbin_sumbits64(x);
/* Iterate until a solution is found */
while (to--) {
if (sbx == 2)
break;
for (r = 0; r != p; r++) {
if (ntable[r] == 0)
continue;
y = x ^ mbin_xor2_rol_mod_64(x, r, p);
sby = mbin_sumbits64(y);
if (sby <= sbx) {
z += (1ULL << ntable[r]);
x = y;
sbx = sby;
break;
}
}
/* invert value */
if (r == p) {
y = x ^ ((1ULL << p) - 1ULL);
sby = mbin_sumbits64(y);
x = y;
sbx = sby;
}
}
if (to == (uint8_t)-1)
return (0);
/* shift down */
while (!(x & 1ULL)) {
z += d2;
x /= 2ULL;
}
/* locate the second bit */
for (r = 1; r != p; r++) {
if (x & (1ULL << r))
break;
}
/* properly MOD the "z" variable */
if (ntable[r])
z = (mask + (1ULL << ntable[r]) - (z % mask)) % mask;
else
z = (mask - (z % mask)) % mask;
return (z);
}
uint64_t
mbin_xor2_is_div_by_3_64(uint64_t x)
{
return (mbin_sumbits64(x) & 1);
}
uint64_t
mbin_xor2_sliced_exp_64(uint64_t x, uint64_t y,
uint64_t base, uint64_t mod)
{
uint64_t r;
uint64_t bb;
uint8_t msb;
uint8_t a;
uint8_t b;
msb = mbin_sumbits64(mbin_msb64(mod) - 1ULL);
for (a = 0; a != msb; a++) {
if (y & (1ULL << a)) {
bb = base;
r = 0;
for (b = 0; b != msb; b++) {
r |= (mbin_sumbits64(x & bb) & 1) << b;
bb = mbin_xor2_mul_mod_any_64(2, bb, mod);
}
x = r;
}
base = mbin_xor2_mul_mod_any_64(base, base, mod);
}
return (x);
}
uint8_t
mbin_xor2_is_mirror_64(uint64_t x)
{
uint8_t end;
uint64_t rev;
uint64_t mask;
uint8_t found;
found = 0;
while (x > 1) {
mask = mbin_lsb64(x) - 1ULL;
end = mbin_sumbits64(mask);
x >>= end;
mask = mbin_msb64(x) - 1ULL;
end = mbin_sumbits64(mask);
rev = mbin_bitrev64(x << (63 - end));
if (rev != x)
break;
found++;
x >>= ((end + 1) / 2);
}
return (found);
}
uint64_t
mbin_xor2_reduce_64(uint64_t x, uint8_t p)
{
if (x & (1ULL << (p - 1)))
x ^= (1ULL << p) - 1ULL;
return (x);
}
uint64_t
mbin_xor2_exp_mod_64(uint64_t x, uint64_t y, uint8_t p)
{
uint64_t r = 1;
uint8_t n = 1;
do {
if (y & 1) {
uint64_t z;
z = mbin_xor2_multi_square_mod_64(x, n, p);
if (r == 1)
r = z;
else
r = mbin_xor2_mul_mod_64(r, z, p);
}
n *= 2;
if (n >= p)
n -= p;
} while ((y /= 2));
return (r);
}
uint64_t
mbin_xor2_exp_64(uint64_t x, uint64_t y)
{
uint64_t r = 1;
while (y) {
if (y & 1)
r = mbin_xor2_mul_64(r, x);
x = mbin_xor2_mul_64(x, x);
y /= 2;
}
return (r);
}
uint64_t
mbin_xor2_exp_mod_any_64(uint64_t x, uint64_t y, uint64_t p)
{
uint64_t r = 1;
while (y) {
if (y & 1)
r = mbin_xor2_mul_mod_any_64(r, x, p);
x = mbin_xor2_mul_mod_any_64(x, x, p);
y /= 2;
}
return (r);
}
uint32_t
mbin_xor2_exp_mod_any_32(uint32_t x, uint32_t y, uint32_t p)
{
uint32_t r = 1;
while (y) {
if (y & 1)
r = mbin_xor2_mul_mod_any_32(r, x, p);
x = mbin_xor2_mul_mod_any_32(x, x, p);
y /= 2;
}
return (r);
}
uint64_t
mbin_xor2_neg_mod_64(uint64_t x, uint8_t p)
{
uint8_t n = p - 2;
uint64_t r = 1;
while (n--) {
x = mbin_xor2_mul_mod_64(x, x, p);
r = mbin_xor2_mul_mod_64(r, x, p);
}
return (r);
}
uint64_t
mbin_xor2_log_mod_64(uint64_t x, uint8_t p)
{
uint64_t mask = (1ULL << p) - 1ULL;
uint64_t r = mask ^ 1ULL;
uint64_t y = 0;
/* Check for NUL */
if (x == 0)
return (0);
if (x & 1)
x = ~x & mask;
else
x = x & mask;
while (x != r) {
r = mbin_xor2_mul_mod_64(r, p, p);
if (r & 1)
r = ~r & mask;
if (y > mask)
return (0);
y++;
}
return (y);
}
uint64_t
mbin_xor2_mul_64(uint64_t x, uint64_t y)
{
uint64_t temp[4];
uint64_t r = 0;
uint8_t n;
/* optimise */
temp[0] = 0;
temp[1] = x;
temp[2] = 2 * x;
temp[3] = x ^ (2 * x);
for (n = 0; n != 64; n += 2) {
r ^= temp[y & 3] << n;
y /= 4;
}
return (r);
}
uint64_t
mbin_xor2_mul_mod_64(uint64_t x, uint64_t y, uint8_t p)
{
uint64_t temp[4];
uint64_t rl;
uint64_t rh = 0;
uint64_t z;
uint8_t n;
/* optimise */
temp[0] = 0;
temp[1] = x;
temp[2] = 2 * x;
temp[3] = x ^ (2 * x);
rl = temp[y & 3];
y /= 4;
for (n = 2; n < p; n += 2) {
z = temp[y & 3];
rl ^= z << n;
rh ^= z >> (64 - n);
y /= 4;
}
n = (64 % p);
if (n != 0)
rh = (rh >> n) | (rh << (64 - n));
rl ^= rh;
do {
z = (rl >> p);
rl = (rl & ((1ULL << p) - 1ULL)) ^ z;
} while (z);
return (rl);
}
uint64_t
mbin_xor2_mul_mod_any_64(uint64_t x, uint64_t y, uint64_t mod)
{
uint64_t temp[4];
uint64_t rl = 0;
uint64_t rh = 0;
uint8_t n;
/* optimise */
temp[0] = 0;
temp[1] = x;
temp[2] = 2 * x;
temp[3] = x ^ (2 * x);
rl ^= temp[y & 3];
y /= 4;
for (n = 2; n != 64; n += 2) {
rl ^= temp[y & 3] << n;
rh ^= temp[y & 3] >> (64 - n);
y /= 4;
}
return (mbin_xor2_mod_128(rh, rl, mod));
}
uint64_t
mbin_xor2_mod_len_slow_64(uint64_t base, uint64_t mod)
{
uint64_t x, y;
for (x = 1, y = 2; y != 1; x++)
y = mbin_xor2_mul_mod_any_64(y, base, mod);
return (x);
}
uint32_t
mbin_xor2_mul_mod_any_32(uint32_t x, uint32_t y, uint32_t mod)
{
uint64_t temp[4];
uint64_t r = 0;
uint8_t n;
/* optimise */
temp[0] = 0;
temp[1] = x;
temp[2] = 2ULL * (uint64_t)x;
temp[3] = x ^ (2ULL * (uint64_t)x);
for (n = 0; n != 32; n += 2) {
r ^= temp[y & 3] << n;
y /= 4;
}
return (mbin_xor2_mod_64(r, mod));
}
uint64_t
mbin_xor2_mod_128(uint64_t rh, uint64_t rl, uint64_t mod)
{
if (rh != 0) {
uint64_t msb = mbin_msb64(mod);
uint8_t x;
rh = mbin_xor2_mod_64(rh, mod);
for (x = 0; x != 64; x++) {
rh <<= 1;
if (rh & msb)
rh ^= mod;
}
rl ^= rh;
}
return (mbin_xor2_mod_64(rl, mod));
}
uint64_t
mbin_xor2_mod_64(uint64_t x, uint64_t div)
{
uint64_t msb = mbin_msb64(div);
uint64_t temp[4];
uint8_t n;
uint8_t shift;
if (x < msb)
return (x);
shift = 62 - mbin_sumbits64(msb - 1);
/* optimise */
temp[0] = 0;
temp[1] = div << shift;
temp[2] = (2 * temp[1]);
temp[3] = (2 * temp[1]);
if (temp[2] & (1ULL << 62))
temp[2] ^= temp[1];
else
temp[3] ^= temp[1];
for (n = 0; n <= shift; n += 2) {
x ^= temp[(x >> 62) & 3];
x *= 4;
}
if ((shift & 1) && (x & (1ULL << 63)))
x ^= 2 * temp[1];
x >>= n;
return (x);
}
uint64_t
mbin_xor2_mod_simple_64(uint64_t x, uint64_t div)
{
uint64_t msb = mbin_msb64(div);
uint8_t n;
uint8_t shift;
if (x < msb)
return (x);
shift = 63 - mbin_sumbits64(msb - 1);
for (n = shift; n != (uint8_t)-1; n--) {
if (x & (msb << n))
x ^= (div << n);
}
return (x);
}
uint32_t
mbin_xor2_mod_32(uint32_t x, uint32_t div)
{
uint32_t msb = mbin_msb32(div);
uint32_t temp[4];
uint8_t n;
uint8_t shift;
if (x < msb)
return (x);
shift = 30 - mbin_sumbits32(msb - 1);
/* optimise */
temp[0] = 0;
temp[1] = div << shift;
temp[2] = (2 * temp[1]);
temp[3] = (2 * temp[1]);
if (temp[2] & (1ULL << 30))
temp[2] ^= temp[1];
else
temp[3] ^= temp[1];
for (n = 0; n <= shift; n += 2) {
x ^= temp[(x >> 30) & 3];
x *= 4;
}
if ((shift & 1) && (x & (1U << 31)))
x ^= 2 * temp[1];
x >>= n;
return (x);
}
uint64_t
mbin_xor2_div_64(uint64_t x, uint64_t div)
{
uint64_t msb = mbin_msb64(div);
uint64_t xsb = mbin_msb64(x);
uint64_t r = 0;
uint8_t n;
if (x == 0 || div == 0)
return (0);
if (xsb < msb)
return (0);
for (n = 0; n != 64; n++) {
if (xsb & (msb << n))
break;
}
do {
if (x & (msb << n)) {
x ^= (div << n);
r |= (1ULL << n);
}
} while (n--);
return (r);
}
uint64_t
mbin_xor2_div_odd_64(uint64_t x, uint64_t div)
{
uint64_t r = 0;
uint8_t n;
div |= 1;
for (n = 0; n != 64; n++) {
if (x & (1ULL << n)) {
r |= (1ULL << n);
x ^= (div << n);
}
}
return (r);
}
uint64_t
mbin_xor2_multiply_func_64(uint64_t x, uint64_t y)
{
uint64_t retval = 0;
uint8_t a, b;
for (a = 0; a != 32; a++) {
for (b = a + 1; (a + b) < 64; b++)
retval += (((x >> a) ^ (y >> b)) & 1ULL) << (a + b);
}
return (retval);
}
uint64_t
mbin_xor2_div_mod_any_64(uint64_t rem, uint64_t div, uint64_t mod)
{
uint64_t msb = mbin_msb64(mod);
uint32_t nbit = mbin_sumbits64(msb - 1ULL);
uint32_t x;
uint32_t y;
uint64_t table[64][2];
uint64_t t;
memset(table, 0, sizeof(table[0]) * nbit);
/* build binary equation set in table */
for (x = 0; x != nbit; x++)
table[x][1] = 1ULL << x;
for (x = 0, t = div; x != nbit; x++) {
for (y = 0; y != nbit; y++)
table[y][0] |= ((t >> y) & 1ULL) << x;
t <<= 1;
if (t & msb)
t ^= mod;
}
/* solve binary equation set */
for (x = 0; x != nbit; x++) {
if (table[x][0] == 0)
continue;
t = mbin_lsb64(table[x][0]);
for (y = 0; y != nbit; y++) {
if (x == y)
continue;
if (table[y][0] & t) {
table[y][0] ^= table[x][0];
table[y][1] ^= table[x][1];
}
}
}
/* compute answer */
for (t = x = 0; x != nbit; x++) {
t |= mbin_lsb64(table[x][0]) *
(mbin_sumbits64(table[x][1] & rem) & 1ULL);
}
return (t);
}
uint64_t
mbin_xor2_lin_mul_64(uint64_t x, uint64_t y, uint8_t p)
{
x = mbin_xor2_exp3_mod_64(1, x, p);
y = mbin_xor2_exp_mod_64(x, y, p);
return (mbin_xor2_log3_mod_64(y, p));
}
uint64_t
mbin_xor2_bit_reduce_mod_64(uint64_t x, uint8_t p)
{
if (mbin_sumbits64(x) > (p / 2))
x = x ^ ((1ULL << p) - 1ULL);
return (x);
}
uint64_t
mbin_xor2_factor_slow_64(uint64_t x)
{
uint64_t y;
uint64_t z;
if (x != 0 && !(x & 1))
return (2);
z = 2 * mbin_sqrt_64(x);
for (y = 3; y <= z; y += 2) {
if (mbin_xor2_mod_64(x, y) == 0)
return (y);
}
return (0);
}
uint8_t
mbin_xor2_find_mod_64(uint32_t *pbit)
{
uint32_t x;
uint32_t y;
uint32_t power = *pbit;
while (1) {
if (power >= (1U << 24))
return (1); /* not found */
/*
* Find a suitable modulus,
* typically two power of a prime:
*/
y = 1;
x = 0;
while (1) {
y *= 2;
if (y >= power)
y -= power;
x++;
if (y == 1)
break;
if (x == power)
break;
}
if ((x == (power - 1)) && (y == 1))
break;
power++;
}
*pbit = power;
return (0);
}
/*
* The following function is used to solve binary matrices.
*/
uint8_t
mbin_xor2_inv_mat_mod_any_32(uint32_t *table,
struct mbin_poly_32 *poly, uint32_t size)
{
uint32_t temp;
uint32_t x;
uint32_t y;
uint32_t z;
uint32_t u;
uint8_t retval = 0;
/* invert matrix */
for (y = 0; y != size; y++) {
/* find non-zero entry in row */
for (x = 0; x != size; x++) {
if (table[(size * x) + y] != 0)
goto found_non_zero;
}
retval = 1; /* failure */
continue;
found_non_zero:
/* normalise row */
temp = table[(size * x) + y];
/* invert temp - negative */
temp = mbin_xor2_exp_mod_any_32(temp,
poly->length - 1, poly->poly);
for (z = 0; z != (2 * size); z++) {
table[(size * z) + y] =
mbin_xor2_mul_mod_any_32(table[(size * z) + y],
temp, poly->poly);
}
table[(size * x) + y] = 1;
/* subtract row */
for (z = 0; z != size; z++) {
if ((z != y) && (table[(size * x) + z] != 0)) {
temp = table[(size * x) + z];
for (u = 0; u != (2 * size); u++) {
table[(size * u) + z] =
table[(size * u) + z] ^
mbin_xor2_mul_mod_any_32(temp,
table[(size * u) + y], poly->poly);
}
if (table[(size * x) + z] != 0)
return (2); /* failure */
}
}
}
/* sort matrix */
for (y = 0; y != size; y++) {
for (x = 0; x != size; x++) {
if (table[(size * x) + y] != 0) {
if (x != y) {
/* wrong order - swap */
for (z = 0; z != (2 * size); z++) {
temp = table[(size * z) + x];
table[(size * z) + x] =
table[(size * z) + y];
table[(size * z) + y] = temp;
}
y--;
}
break;
}
}
if (x == size)
retval = 3; /* failure */
}
return (retval); /* success */
}
uint64_t
mbin_xor2_faculty_64(uint64_t n)
{
uint64_t r = 1;
while (n) {
r = mbin_xor2_mul_64(r, n);
n--;
}
return (r);
}
uint64_t
mbin_xor2_coeff_64(int64_t n, int64_t x)
{
uint64_t shift = 1ULL << 32;
uint64_t lsb;
uint64_t y;
uint64_t fa = 1ULL;
uint64_t fb = 1ULL;
/* check limits */
if ((n < 0) || (x < 0))
return (0);
if (x > n)
return (0);
/* handle special case */
if (x == n || x == 0)
return (1ULL);
for (y = 0; y != x; y++) {
lsb = (y - n) & (n - y);
shift *= lsb;
fa = mbin_xor2_mul_64(fa, (n - y) / lsb);
lsb = (-y - 1) & (y + 1);
shift /= lsb;
fb = mbin_xor2_mul_64(fb, (y + 1) / lsb);
}
return (mbin_xor2_mul_64(mbin_xor2_div_odd_64(fa, fb), (shift >> 32)));
}
/* greatest common divisor for CRC's (modified Euclid equation) */
uint64_t
mbin_xor2_gcd_64(uint64_t a, uint64_t b)
{
uint64_t an;
uint64_t bn;
while (b != 0) {
an = b;
bn = mbin_xor2_mod_64(a, b);
a = an;
b = bn;
}
return (a);
}
/* extended Euclidean equation for CRC */
void
mbin_xor2_gcd_extended_64(uint64_t a, uint64_t b, uint64_t *pa, uint64_t *pb)
{
uint64_t x = 0;
uint64_t y = 1;
uint64_t lastx = 1;
uint64_t lasty = 0;
uint64_t q;
uint64_t an;
uint64_t bn;
while (b != 0) {
q = mbin_xor2_div_64(a, b);
an = b;
bn = mbin_xor2_mod_64(a, b);
a = an;
b = bn;
an = lastx ^ mbin_xor2_mul_64(q, x);
bn = x;
x = an;
lastx = bn;
an = lasty ^ mbin_xor2_mul_64(q, y);
bn = y;
y = an;
lasty = bn;
}
*pa = lastx;
*pb = lasty;
}
void
mbin_xor_print_mat_32(const uint32_t *table, uint32_t size, uint8_t print_invert)
{
uint32_t temp;
uint32_t x;
uint32_t y;
uint32_t off;
uint8_t no_solution = 0;
off = print_invert ? size : 0;
for (y = 0; y != size; y++) {
printf("0x%02x | ", y);
for (x = 0; x != size; x++) {
temp = table[((x + off) * size) + y];
printf("0x%08x", temp);
if (x != (size - 1))
printf(", ");
}
printf(";\n");
}
if (no_solution)
printf("this matrix has no solution due to undefined bits!\n");
}
/*
* ========================================================================
* BASE-3 XOR
* ========================================================================
*/
#define MBIN_XOR3_POLY(p,q) ((1ULL << (p)) | (1ULL << (q)) | (((p) & 2) ? 1ULL : 2ULL))
uint64_t
mbin_xor3_64(uint64_t a, uint64_t b)
{
const uint64_t K = 0x5555555555555555ULL;
uint64_t d;
uint64_t e;
d = b & K;
e = (b & ~K) / 2;
a += d;
b = a & (a / 2) & K;
a ^= b | (2 * b);
a += e;
b = a & (a / 2) & K;
a ^= b | (2 * b);
a += e;
b = a & (a / 2) & K;
a ^= b | (2 * b);
return (a);
}
uint64_t
mbin_xor3_mul_mod_64(uint64_t x, uint64_t y, uint8_t p, uint8_t q)
{
uint64_t poly = MBIN_XOR3_POLY(p, q);
uint64_t r = 0;
uint8_t n;
for (n = 0; n != 64; n += 2) {
uint8_t m = (y >> n) & 3;
while (m--)
r = mbin_xor3_64(r, x);
x <<= 2;
while (x & (3ULL << p))
x = mbin_xor3_64(x, poly);
}
return (r);
}
uint64_t
mbin_xor3_exp_slow_64(uint64_t x, uint64_t y)
{
uint64_t r = 1;
while (y) {
if (y & 1)
r = mbin_xor3_mul_64(r, x);
x = mbin_xor3_mul_64(x, x);
y /= 2;
}
return (r);
}
uint64_t
mbin_xor3_multiply_plain_64(uint64_t a, uint64_t b, uint64_t mod)
{
uint8_t lmax = mbin_sumbits64(mbin_msb64(mod) - 1ULL) / 2;
uint8_t x;
uint64_t r;
uint64_t s;
for (r = 0, s = 1, x = 0; x != lmax; x++) {
if ((a >> (2 * x)) & 1)
r = mbin_xor3_64(s, r);
if ((a >> (2 * x)) & 2) {
r = mbin_xor3_64(s, r);
r = mbin_xor3_64(s, r);
}
s = mbin_xor3_mul_mod_any_64(s, b, mod);
}
return (r);
}
uint64_t
mbin_xor3_qubic_64(uint64_t x)
{
uint64_t r = 0;
uint8_t n;
for (n = 0; n != 16; n++)
r |= (x & (3ULL << (2 * n))) << (4 * n);
return (r);
}
uint64_t
mbin_xor3_qubic_mod_64(uint64_t x, uint64_t p)
{
uint64_t r = 0;
uint64_t m = 1;
uint64_t msb;
msb = mbin_msb64(p);
if (msb & 0xAAAAAAAAAAAAAAAAULL)
msb /= 2ULL;
msb *= 3ULL;
while (x) {
while (x & 3) {
r = mbin_xor3_64(r, m);
x--;
}
x >>= 2;
m <<= 2;
while (m & msb)
m = mbin_xor3_64(m, p);
m <<= 2;
while (m & msb)
m = mbin_xor3_64(m, p);
m <<= 2;
while (m & msb)
m = mbin_xor3_64(m, p);
}
return (r);
}
uint64_t
mbin_xor3_exp_64(uint64_t x, uint64_t y)
{
uint64_t r = 1;
while (y) {
while (y % 3) {
r = mbin_xor3_mul_64(r, x);
y--;
}
x = mbin_xor3_qubic_64(x);
y /= 3;
}
return (r);
}
uint64_t
mbin_xor3_mod_64(uint64_t rem, uint64_t mod)
{
uint8_t sr;
uint8_t sm;
if (rem == 0 || mod == 0)
return (0);
sr = mbin_sumbits32(mbin_msb32(rem) - 1);
sr &= ~1;
sm = mbin_sumbits32(mbin_msb32(mod) - 1);
sm &= ~1;
if (sm > sr)
return (rem);
while (1) {
while (rem & (3 << sr))
rem = mbin_xor3_64(rem, mod << (sr - sm));
if (sr == sm)
break;
sr -= 2;
}
return (rem);
}
uint64_t
mbin_xor3_div_64(uint64_t rem, uint64_t div)
{
uint64_t r = 0;
uint8_t sr;
uint8_t sd;
if (rem == 0 || div == 0)
return (0);
sr = mbin_sumbits32(mbin_msb32(rem) - 1);
sr &= ~1;
sd = mbin_sumbits32(mbin_msb32(div) - 1);
sd &= ~1;
if (sd > sr)
return (0);
while (1) {
while (rem & (3 << sr)) {
rem = mbin_xor3_64(rem, div << (sr - sd));
r = mbin_xor3_64(r, 2 << (sr - sd));
}
if (sr == sd)
break;
sr -= 2;
}
return (r);
}
uint64_t
mbin_xor3_mul_64(uint64_t x, uint64_t y)
{
uint64_t r = 0;
uint8_t n;
for (n = 0; n != 64; n += 2) {
uint8_t m = (y >> n) & 3;
while (m--)
r = mbin_xor3_64(r, x);
x <<= 2;
}
return (r);
}
uint64_t
mbin_xor3_mul_mod_any_64(uint64_t x, uint64_t y, uint64_t p)
{
uint64_t r = 0;
uint64_t msb = mbin_msb64(p);
uint8_t n;
if (msb & 0xAAAAAAAAAAAAAAAAULL)
msb /= 2;
msb = 3ULL * msb;
for (n = 0; n != 64; n += 2) {
uint8_t m = (y >> n) & 3;
while (m--)
r = mbin_xor3_64(r, x);
x <<= 2;
while (x & msb)
x = mbin_xor3_64(x, p);
}
return (r);
}
uint64_t
mbin_xor3_factor_slow_64(uint64_t x)
{
uint64_t y;
uint64_t z;
for (y = 1; y <= x; y++) {
z = (2 * y) | 1;
if (z & (z / 2) & 0x5555555555555555ULL)
continue;
if (mbin_xor3_mod_64(x, z) == 0)
return (z);
}
return (0);
}
uint32_t
mbin_xor3_mul_mod_any_32(uint32_t x, uint32_t y, uint32_t p)
{
uint32_t r = 0;
uint32_t msb = mbin_msb32(p);
uint8_t n;
if (msb & 0xAAAAAAAAUL)
msb /= 2;
msb = 3 * msb;
for (n = 0; n != 32; n += 2) {
uint8_t m = (y >> n) & 3;
while (m--)
r = mbin_xor3_32(r, x);
x <<= 2;
while (x & msb)
x = mbin_xor3_32(x, p);
}
return (r);
}
uint64_t
mbin_xor3_exp_mod_64(uint64_t x, uint64_t y, uint8_t p, uint8_t q)
{
uint64_t r = 1;
while (y) {
if (y & 1)
r = mbin_xor3_mul_mod_64(r, x, p, q);
x = mbin_xor3_mul_mod_64(x, x, p, q);
y /= 2;
}
return (r);
}
uint64_t
mbin_xor3_exp_slow_mod_any_64(uint64_t x, uint64_t y, uint64_t p)
{
uint64_t r = 1;
while (y) {
if (y & 1)
r = mbin_xor3_mul_mod_any_64(r, x, p);
x = mbin_xor3_mul_mod_any_64(x, x, p);
y /= 2;
}
return (r);
}
uint64_t
mbin_xor3_exp_mod_any_64(uint64_t x, uint64_t y, uint64_t p)
{
uint64_t r = 1;
while (y) {
while (y % 3) {
r = mbin_xor3_mul_mod_any_64(r, x, p);
y--;
}
x = mbin_xor3_qubic_mod_64(x, p);
y /= 3;
}
return (r);
}
uint64_t
mbin_xor3_neg_mod_64(uint64_t x, uint8_t p, uint8_t q)
{
uint64_t len;
uint8_t n;
for (len = 1ULL, n = 0; n != p; n += 2)
len *= 3ULL;
len -= 2;
return (mbin_xor3_exp_mod_64(x, len, p, q));
}
uint8_t
mbin_xor3_find_mod_64(uint8_t *pbit, uint8_t *qbit, uint64_t *plen)
{
uint64_t len;
uint8_t power = *pbit;
uint8_t q;
uint8_t x;
if (power < 4)
return (1);
if (power & 1)
power++;
if (~power & 2)
power += 2;
for (len = 1, x = 0; x != power; x += 2)
len *= 3ULL;
for (q = 2; q < power; q++) {
if (mbin_xor3_exp_mod_64(4, len, power, q) == 4)
break;
}
if (q >= power)
return (1);
*pbit = power;
*qbit = q;
if (plen)
*plen = len;
return (0);
}
/*
* ========================================================================
* BASE-2 VECTOR XOR
* ========================================================================
*/
struct mbin_xor2v_64 mbin_xor2v_zero_64 = {0, 1};
struct mbin_xor2v_64 mbin_xor2v_unit_64 = {1, 3};
struct mbin_xor2v_64 mbin_xor2v_nega_64 = {1, 0};
struct mbin_xor2v_32 mbin_xor2v_zero_32 = {0, 1};
struct mbin_xor2v_32 mbin_xor2v_unit_32 = {1, 3};
struct mbin_xor2v_32 mbin_xor2v_nega_32 = {1, 0};
static uint64_t
mbin_xor2_ungray_mod_64(uint64_t x, uint8_t p)
{
uint8_t q;
/* assuming that input has even parity */
for (q = 0; q != (p - 1); q++) {
if (x & (1ULL << q))
x ^= (2ULL << q);
}
return (x);
}
struct mbin_xor2v_64
mbin_xor2v_mul_mod_64(struct mbin_xor2v_64 x, struct mbin_xor2v_64 y, uint8_t p)
{
struct mbin_xor2v_64 t;
uint64_t val;
val = y.a1 ^ y.a0 ^ mbin_xor2_rol_mod_64(y.a0, 1, p);
t.a0 = mbin_xor2_mul_mod_64(x.a0, val, p) ^
mbin_xor2_mul_mod_64(x.a1, y.a0, p);
t.a1 = mbin_xor2_mul_mod_64(x.a0, y.a0, p) ^
mbin_xor2_mul_mod_64(x.a1, y.a1, p);
return (t);
}
struct mbin_xor2v_64
mbin_xor2v_mul_mod_any_64(struct mbin_xor2v_64 x, struct mbin_xor2v_64 y,
uint64_t p)
{
struct mbin_xor2v_64 t;
uint64_t val;
val = y.a1 ^ mbin_xor2_mul_mod_any_64(y.a0, 3, p);
t.a0 = mbin_xor2_mul_mod_any_64(x.a0, val, p) ^
mbin_xor2_mul_mod_any_64(x.a1, y.a0, p);
t.a1 = mbin_xor2_mul_mod_any_64(x.a0, y.a0, p) ^
mbin_xor2_mul_mod_any_64(x.a1, y.a1, p);
return (t);
}
struct mbin_xor2v_32
mbin_xor2v_mul_mod_any_32(struct mbin_xor2v_32 x, struct mbin_xor2v_32 y,
uint32_t p)
{
struct mbin_xor2v_32 t;
uint32_t val;
val = y.a1 ^ mbin_xor2_mul_mod_any_32(y.a0, 3, p);
t.a0 = mbin_xor2_mul_mod_any_32(x.a0, val, p) ^
mbin_xor2_mul_mod_any_32(x.a1, y.a0, p);
t.a1 = mbin_xor2_mul_mod_any_32(x.a0, y.a0, p) ^
mbin_xor2_mul_mod_any_32(x.a1, y.a1, p);
return (t);
}
struct mbin_xor2v_64
mbin_xor2v_square_mod_64(struct mbin_xor2v_64 x, uint8_t p)
{
struct mbin_xor2v_64 t;
uint64_t val;
val = mbin_xor2_square_mod_64(x.a0, p);
t.a0 = val ^ mbin_xor2_rol_mod_64(val, 1, p);
t.a1 = val ^ mbin_xor2_square_mod_64(x.a1, p);
return (t);
}
struct mbin_xor2v_64
mbin_xor2v_root_mod_64(struct mbin_xor2v_64 x, uint8_t p)
{
struct mbin_xor2v_64 t;
/* assuming that "x.a0" has even parity */
t.a0 = mbin_xor2_ungray_mod_64(x.a0, p);
t.a0 = mbin_xor2_root_mod_64(t.a0, p);
t.a1 = t.a0 ^ mbin_xor2_root_mod_64(x.a1, p);
#if 0
/* the other solution */
t.a0 ^= (1ULL << p) - 1ULL;
t.a1 ^= (1ULL << p) - 1ULL;
#endif
return (t);
}
uint64_t
mbin_xor2v_log_mod_64(struct mbin_xor2v_64 x, uint8_t p)
{
uint64_t r = 0;
/* TODO: Optimise */
while (x.a0 != mbin_xor2v_zero_64.a0 ||
x.a1 != mbin_xor2v_zero_64.a1) {
x = mbin_xor2v_mul_mod_64(x, mbin_xor2v_nega_64, p);
r++;
}
return (r);
}
struct mbin_xor2v_64
mbin_xor2v_neg_mod_64(struct mbin_xor2v_64 x, uint8_t p)
{
struct mbin_xor2v_64 t;
/* simply swap */
t.a0 = x.a1;
t.a1 = x.a0;
/* adjust by adding one */
t = mbin_xor2v_mul_mod_64(t, mbin_xor2v_unit_64, p);
return (t);
}
struct mbin_xor2v_32
mbin_xor2v_neg_mod_any_32(struct mbin_xor2v_32 x, uint32_t p)
{
struct mbin_xor2v_32 t;
/* simply swap */
t.a0 = x.a1;
t.a1 = x.a0;
/* adjust by adding one */
t = mbin_xor2v_mul_mod_any_32(t, mbin_xor2v_unit_32, p);
return (t);
}
struct mbin_xor2v_64
mbin_xor2v_neg_sub_unit_mod_64(struct mbin_xor2v_64 x, uint8_t p)
{
struct mbin_xor2v_64 t;
/* simply swap */
t.a0 = x.a1;
t.a1 = x.a0;
return (t);
}
struct mbin_xor2v_64
mbin_xor2v_exp_mod_64(struct mbin_xor2v_64 x, uint64_t y, uint8_t p)
{
struct mbin_xor2v_64 r = mbin_xor2v_zero_64;
while (y) {
if (y & 1)
r = mbin_xor2v_mul_mod_64(r, x, p);
x = mbin_xor2v_mul_mod_64(x, x, p);
y /= 2;
}
return (r);
}
struct mbin_xor2v_32
mbin_xor2v_exp_mod_any_32(struct mbin_xor2v_32 x, uint32_t y, uint32_t p)
{
struct mbin_xor2v_32 r = mbin_xor2v_zero_32;
while (y) {
if (y & 1)
r = mbin_xor2v_mul_mod_any_32(r, x, p);
x = mbin_xor2v_mul_mod_any_32(x, x, p);
y /= 2;
}
return (r);
}
struct mbin_xor2v_32
mbin_xor2v_xor_32(struct mbin_xor2v_32 x, struct mbin_xor2v_32 y)
{
x.a0 ^= y.a0;
x.a1 ^= y.a1;
return (x);
}
void
mbin_xor2v_print_mat_32(const struct mbin_xor2v_32 *table,
uint32_t size, uint8_t print_invert)
{
struct mbin_xor2v_32 temp;
uint32_t x;
uint32_t y;
uint32_t off;
uint8_t no_solution = 0;
off = print_invert ? size : 0;
for (y = 0; y != size; y++) {
printf("0x%02x | ", y);
for (x = 0; x != size; x++) {
temp = table[((x + off) * size) + y];
printf("0x%08x.0x%08x", temp.a0, temp.a1);
if (x != (size - 1))
printf(", ");
}
printf(";\n");
}
if (no_solution)
printf("this matrix has no solution due to undefined bits!\n");
}
/*
* ========================================================================
* BASE-4 XOR
* ========================================================================
*/
uint64_t
mbin_xor4_64(uint64_t a, uint64_t b)
{
const uint64_t K = 0x5555555555555555ULL;
uint64_t d;
uint64_t e;
d = a ^ b;
e = a & b & K;
return (d ^ (2 * e));
}
uint32_t
mbin_xor4_32(uint32_t a, uint32_t b)
{
const uint32_t K = 0x55555555UL;
uint32_t d;
uint32_t e;
d = a ^ b;
e = a & b & K;
return (d ^ (2 * e));
}
uint32_t
mbin_xor4_mul_mod_any_32(uint32_t x, uint32_t y, uint32_t p)
{
uint32_t r = 0;
uint32_t msb = mbin_msb32(p);
uint8_t n;
if (msb & 0xAAAAAAAAUL)
msb /= 2;
msb = 3 * msb;
for (n = 0; n != 32; n += 2) {
uint8_t m = (y >> n) & 3;
while (m--)
r = mbin_xor4_32(r, x);
x <<= 2;
while (x & msb)
x = mbin_xor4_32(x, p);
}
return (r);
}
uint32_t
mbin_xor4_exp_mod_any_32(uint32_t x, uint32_t y, uint32_t p)
{
uint32_t r = 1;
while (y) {
if (y & 1)
r = mbin_xor4_mul_mod_any_32(r, x, p);
x = mbin_xor4_mul_mod_any_32(x, x, p);
y /= 2;
}
return (r);
}
uint32_t
mbin_xor4_multiply_plain_32(uint32_t a, uint32_t b, uint32_t mod)
{
uint8_t lmax = mbin_sumbits32(mbin_msb32(mod) - 1ULL) / 2;
uint8_t x;
uint32_t r;
uint32_t s;
for (r = 0, s = 1, x = 0; x != lmax; x++) {
if ((a >> (2 * x)) & 1)
r = mbin_xor4_32(s, r);
if ((a >> (2 * x)) & 2) {
r = mbin_xor4_32(s, r);
r = mbin_xor4_32(s, r);
}
s = mbin_xor4_mul_mod_any_32(s, b, mod);
}
return (r);
}
uint64_t
mbin_xor4_mul_64(uint64_t a, uint64_t b)
{
uint64_t r = 0;
while (a != 0) {
while (a & 3) {
a--;
r = mbin_xor4_64(r, b);
}
a /= 4;
b *= 4;
}
return (r);
}
uint64_t
mbin_xor4_mod_64(uint64_t rem, uint64_t mod)
{
uint8_t sr;
uint8_t sm;
if (rem == 0 || mod == 0)
return (0);
sr = mbin_sumbits32(mbin_msb32(rem) - 1);
sr &= ~1;
sm = mbin_sumbits32(mbin_msb32(mod) - 1);
sm &= ~1;
if (sm > sr)
return (rem);
while (1) {
uint8_t to = 0;
while ((rem & (3 << sr)) && ++to != 4)
rem = mbin_xor4_32(rem, mod << (sr - sm));
if (to == 4 || sr == sm)
break;
sr -= 2;
}
return (rem);
}
uint64_t
mbin_xor4_div_64(uint64_t rem, uint64_t div)
{
uint8_t sr;
uint8_t sm;
uint64_t ret = 0;
if (rem == 0 || div == 0)
return (0);
sr = mbin_sumbits64(mbin_msb64(rem) - 1);
sr &= ~1;
sm = mbin_sumbits64(mbin_msb64(div) - 1);
sm &= ~1;
if (sm > sr)
return (0);
if (sm == sr)
return (1);
while (1) {
uint8_t to = 0;
while ((rem & (3 << sr)) && ++to != 4) {
rem = mbin_xor4_64(rem, div << (sr - sm));
ret = mbin_xor4_64(ret, 1 << (sr - sm));
}
if (to == 4)
return (0);
if (sr == sm)
break;
sr -= 2;
}
return (ret);
}
uint64_t
mbin_xor4_factor_slow_64(uint64_t x)
{
uint64_t y;
for (y = 4; y < x; y++) {
if (mbin_xor4_mod_64(x, y) == 0)
return (y);
}
return (0);
}
|
C | /*
* usart0.c
*
* Created on: 09/23/18
* Author: Viarus
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include "usart0.h"
#include "usart1.h"
volatile char UART0_RxBuf[UART0_RX_BUF_SIZE];
volatile uint8_t UART0_RxHead;
volatile uint8_t UART0_RxTail;
volatile char UART0_TxBuf[UART0_TX_BUF_SIZE];
volatile uint8_t UART0_TxHead;
volatile uint8_t UART0_TxTail;
void usart0_init(uint16_t ubrr){
// Set baud rate
UBRR0H = (uint8_t)(ubrr >> 8);
UBRR0L = (uint8_t)(ubrr);
// Enable receiver and transmiter
UCSR0B |= ((1 << RXEN0) | (1 << TXEN0)); // Receiver and Transmiter Enable
UCSR0B |= (1 << RXCIE0); // RX Complete Inerrupt Enable
uart1_puts("UART0 configuration finish!\r\n");
}
void uart0_clear(void){
UART0_RxTail = UART0_RxHead;
UART0_TxTail = UART0_TxHead;
}
// USART0 Transmit
void uart0_putc(char data){
uint8_t tmp_head;
tmp_head = (UART0_TxHead + 1) & UART0_TX_BUF_MASK;
while (tmp_head == UART0_TxTail) {}
UART0_TxBuf[tmp_head] = data;
UART0_TxHead = tmp_head;
UCSR0B |= (1 << UDRIE0); // USART Date Register Empty Interrupt Enable
}
void uart0_puts(char *str){
register char sign;
while ((sign = *str++)) uart0_putc(sign);
}
void uart0_putint(int value){
char str[20];
itoa(value, str, 10);
uart0_puts(str);
}
ISR(USART0_UDRE_vect){
if (UART0_TxHead != UART0_TxTail){
UART0_TxTail = (UART0_TxTail + 1) & UART0_TX_BUF_MASK;
UDR0 = UART0_TxBuf[UART0_TxTail];
}
else {
UCSR0B &= ~(1 << UDRIE0);
}
}
// USART0 Receive
char uart0_getc(void){
if (UART0_RxHead == UART0_RxTail) return 0;
UART0_RxTail = (UART0_RxTail + 1) & UART0_RX_BUF_MASK;
return UART0_RxBuf[UART0_RxTail];
}
ISR(USART0_RX_vect){
uint8_t tmp_head;
char data;
data = UDR0;
tmp_head = (UART0_RxHead + 1) & UART0_RX_BUF_MASK;
if (tmp_head == UART0_RxTail){
uart1_puts("UART0 RECEIVE ERROR\r\n");
}
else {
UART0_RxHead = tmp_head;
UART0_RxBuf[tmp_head] = data;
}
}
//------------------------------------------------------------------------------
// Cursor handling
//------------------------------------------------------------------------------
void usart0_cursor_positioning(uint8_t row, uint8_t column){
uart0_putc(0x1b);
uart0_putc('[');
uart0_putint(row);
uart0_putc(';');
uart0_putint(column);
uart0_putc('H');
}
void usart0_cursor_up(uint8_t value){
uart0_putc(0x1b);
uart0_putint(value);
uart0_putc('A');
}
void usart0_cursor_down(uint8_t value){
uart0_putc(0x1b);
uart0_putint(value);
uart0_putc('B');
}
void usart0_cursor_forward(uint8_t value){
uart0_putc(0x1b);
uart0_putint(value);
uart0_putc('C');
}
void usart0_cursor_backward(uint8_t value){
uart0_putc(0x1b);
uart0_putint(value);
uart0_putc('D');
}
void usart0_cursor_save(void){
uart0_putc(0x1b);
uart0_putint(7);
}
void usart0_cursor_restore(void){
uart0_putc(0x1b);
uart0_putint(8);
}
void usart0_cursor_invisible(void){
uart0_putc(0x1b);
uart0_putc('[');
uart0_putc('?');
uart0_putint(25);
uart0_putc('l');
}
void usart0_cursor_visible(void){
uart0_putc(0x1b);
uart0_putc('[');
uart0_putc('?');
uart0_putint(25);
uart0_putc('h');
}
//------------------------------------------------------------------------------
// Erasing text
//------------------------------------------------------------------------------
void usart0_erase_line_usart0_cursor_end(void){
uart0_putc(0x1b);
uart0_puts("[0K");
}
void usart0_erase_line_beginning_cursor(void){
uart0_putc(0x1b);
uart0_puts("[1K");
}
void usart0_erase_line(void){
uart0_putc(0x1b);
uart0_puts("[2K");
}
void usart0_erase_down(void){
uart0_putc(0x1b);
uart0_puts("[0J");
}
void usart0_erase_up(void){
uart0_putc(0x1b);
uart0_puts("[1J");
}
void usart0_erase_screen(void){
uart0_putc(0x1b);
uart0_puts("[2J");
}
//------------------------------------------------------------------------------
// General text attributes
//------------------------------------------------------------------------------
void usart0_attrreset_all(void){
uart0_putc(0x1b);
uart0_puts("[0m");
}
void usart0_attrbright(void){
uart0_putc(0x1b);
uart0_puts("[1m");
}
void usart0_attrdim(void){
uart0_putc(0x1b);
uart0_puts("[2m");
}
void usart0_attrstandout(void){
uart0_putc(0x1b);
uart0_puts("[3m");
}
void usart0_attrunderscore(void){
uart0_putc(0x1b);
uart0_puts("[4m");
}
void usart0_attrblink(void){
uart0_putc(0x1b);
uart0_puts("[5m");
}
void usart0_attrreverse(void){
uart0_putc(0x1b);
uart0_puts("[7m");
}
void usart0_attrhidden(void){
uart0_putc(0x1b);
uart0_puts("[8m");
}
//------------------------------------------------------------------------------
// Foreground colouring
//------------------------------------------------------------------------------
void usart0_foreground_black(void){
uart0_putc(0x1b);
uart0_puts("[30m");
}
void usart0_foreground_red(void){
uart0_putc(0x1b);
uart0_puts("[31m");
}
void usart0_foreground_green(void){
uart0_putc(0x1b);
uart0_puts("[32m");
}
void usart0_foreground_yellow(void){
uart0_putc(0x1b);
uart0_puts("[33m");
}
void usart0_foreground_blue(void){
uart0_putc(0x1b);
uart0_puts("[34m");
}
void usart0_foreground_magenta(void){
uart0_putc(0x1b);
uart0_puts("[35m");
}
void usart0_foreground_cyan(void){
uart0_putc(0x1b);
uart0_puts("[36m");
}
void usart0_foreground_white(void){
uart0_putc(0x1b);
uart0_puts("[37m");
}
void usart0_foreground_set_default(void){
uart0_putc(0x1b);
uart0_puts("[39m");
}
//------------------------------------------------------------------------------
// Usart0_Background colouring
//------------------------------------------------------------------------------
void usart0_background_black(void){
uart0_putc(0x1b);
uart0_puts("[40m");
}
void usart0_background_red(void){
uart0_putc(0x1b);
uart0_puts("[41m");
}
void usart0_background_green(void){
uart0_putc(0x1b);
uart0_puts("[42m");
}
void usart0_background_yellow(void){
uart0_putc(0x1b);
uart0_puts("[43m");
}
void usart0_background_blue(void){
uart0_putc(0x1b);
uart0_puts("[44m");
}
void usart0_background_magenta(void){
uart0_putc(0x1b);
uart0_puts("[45m");
}
void usart0_background_cyan(void){
uart0_putc(0x1b);
uart0_puts("[46m");
}
void usart0_background_white(void){
uart0_putc(0x1b);
uart0_puts("[47m");
}
void usart0_background_set_default(void){
uart0_putc(0x1b);
uart0_puts("[49m");
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "jnitools.h"
jobject JObjectFromPointer(JNIEnv *jenv, char *className, void *p) {
jclass jc;
jmethodID jmid;
jobject jresult;
jlong jl;
if (p == NULL) return NULL;
jc = (*jenv)->FindClass(jenv, className);
if (jc == NULL) {
printf("ERROR. Class %s not found!\n", className);
return NULL;
}
jmid = (*jenv)->GetStaticMethodID(jenv, jc, "initializeFromPointer", "(J)Ljava/lang/Object;");
if (jmid == NULL) {
printf("ERROR. Method initializeFromPointer() not found!\n");
return NULL;
}
*(void **) &jl = p; /* Need to understand better */
jresult = (*jenv)->CallStaticObjectMethod(jenv, jc, jmid, jl);
return jresult;
}
void *PointerFromJObject(JNIEnv *jenv, jobject jo) {
jclass jc;
jmethodID jmid;
jlong jl;
if (jo == NULL) return NULL;
jc = (*jenv)->GetObjectClass(jenv, jo);
if (jc == NULL) return NULL;
jmid = (*jenv)->GetMethodID(jenv, jc, "self", "()J");
if (jmid == NULL) return NULL;
jl = (*jenv)->CallLongMethod(jenv, jo, jmid);
return *(void **) &jl;
}
|
C |
#include "exercicio3.h"
void *threadCitizen(void *params) {
int result = -1, error = 0;
params_t *par = (params_t *)params;
result = par->worker();
send_sync(0, par->ch, result);
receive(1, par->ch, &error);
if (error)
printf("Thread %d finalizando\n", par->ch);
else {
printf("Thread %d ativa\n", par->ch);
while (1)
;
}
return NULL;
}
void *threadDriver(void *params) {
int *numchannels = (int *)params;
int out = 0;
int vresult[*numchannels];
int verr = -1;
int i = *numchannels;
while (i--) vresult[i] = -1;
i = *numchannels;
while (i--) {
receive(0, i, &out);
vresult[i] = out;
}
verr = compara(vresult, *numchannels);
i = *numchannels;
while (i--) {
send_sync(1, i, verr == i ? 1 : 0);
}
return NULL;
}
int fA() {
int i = rand() % 100;
return i > 30 ? 10 : 0;
}
int fB() {
int i = rand() % 100;
return i > 40 ? 10 : 0;
}
int fC() {
int i = rand() % 100;
return i > 50 ? 10 : 0;
}
int compara(int val[], int size) {
int i = size;
int j = size;
while (i--) {
j = size;
while (j--)
if (val[i] != val[j]) return j;
}
return -1;
}
void send_sync(int inout, int ch, int val) {
// 0 we'll use to receive
// 1 we'll use to send
duplex[inout][ch] = val;
while (duplex[0][ch] != -1)
;
// busy wait because yes
}
void receive(int inout, int ch, int *out) {
while (duplex[inout][ch] == -1)
;
*out = duplex[inout][ch];
duplex[inout][ch] = -1;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int fCountChar(const char *filename)
{
FILE *fp = fopen (filename, "r");
//File doesn't exist or something
if (fp == NULL)
{
printf("Failed opening %s\n", filename);
exit(EXIT_FAILURE);
}
char c;
int count = 0; //Counts characters
//Iterate through file
while ((c = fgetc(fp)) != EOF)
{
count++;
}
fclose(fp);
return count;
}
int fCountWords(const char *filename)
{
FILE *fp = fopen (filename, "r");
//File doesn't exist or something
if (fp == NULL)
{
printf("Failed opening %s\n", filename);
exit(EXIT_FAILURE);
}
char c;
int lastSpace = 1; //Checks if the last character was a space
int count = 0; //Counts words
//Iterate through file
while ((c = fgetc(fp)) != EOF)
{
if (isspace((unsigned char) c))
{
lastSpace = 1;
}
else if (lastSpace)
{
count++;
lastSpace = 0;
}
}
return count;
}
int fCountLines(const char *filename)
{
FILE *fp = fopen (filename, "r");
//File doesn't exist or something
if (fp == NULL)
{
printf("Failed opening %s\n", filename);
exit(EXIT_FAILURE);
}
char c;
int count = 0; //Counts lines
//Iterate through file
while ((c = fgetc(fp)) != EOF)
{
if (c == '\n')
{
count++;
}
}
return count;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Please only use one agrument.");
exit(EXIT_FAILURE);
}
printf("Number of characters in file: %d\n", fCountChar(argv[1]));
printf("Number of words in file: %d\n", fCountWords(argv[1]));
printf("Number of lines in file: %d\n", fCountLines(argv[1]));
return 0;
}
|
C | /**
*
* Infomática I
* Año: 2019
* Grupo Nº: 6
* Nombres de alumnos: Albanesi, Tomas Agustin
Gonzalez Perez, Jose
Mella, Camila
Alvarez, Gerson
Magallanes, Claudio
* TP Nº1 Guia de Trabajos Practicos 2018
* Nº de ejercicio: 5.5 - Ejercicio 5
* Enunciado del ejercicio: Escribir una función denominada my_strlen que recibe como argumento un puntero a una cadena de
caracteres ASCIIZ (ASCII Zero ended, es decir una secuencia de caracteres de texto finalizada en ’\0’), y
retorne un valor entero con la cantidad de caracteres contenidos en la cadena. El caracter terminador no se
incluye en la cuenta.
Condición: No utilizar ninguna función auxiliar definida en el encabezamiento string.h.
* Observaciones: gcc -o ejercicio55 ejercicio55.c funciones.c
*
**/
#include<stdio.h>
#include "lib55.h"
int main(void){
int cant;
int i;
int cant_caracteres=0;
char string[100];
printf("\n - GUIA TP 2018 - EJERCICIO 5.5 - \n\n");
printf("\nIngrese una cadena de caracteres: ");
scanf("%[^\n]s",string);
cant = my_strlen(string);
printf("\nLa cantidad de caracteres es: %d\n\n",cant);
return 0;
}
|
C | // Soru1:
//Girilen bir tamsayının üç katını ekrana yazdıran programı yazınız.
#include <stdio.h>
int main(){
int a;
scanf("%d", &a);
a *= 3;
printf("%d\n", a);
} |
C | /*
Even or Odd
*/
#include<stdio.h>
main()
{
int number=0;
printf("enter number\n");
scanf("%d",&number);
number%2 == 0 ? printf("even\n") : printf("odd\n");
}
|
C | #include <stdio.h>
int main(){
int i, n, j, k=0;
scanf("%d", &n);
for(i=1; i<=n; i++){
if(i==(n+1)/2+1)k--;
for(j=1;j<=n;j++){
printf("%d ", k*n+j);
}
k = i<=(n+1)/2 ? k+2:k-2;
printf("\n");
if(i==(n+1)/2 && n%2)k-=2;
}
return 0;
}
|
C | #include "message_buffer.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int shmid;
void *memory_segment=NULL;
int init_buffer(MessageBuffer **buffer) {
/*---------------------------------------*/
/* TODO 1 : init buffer */
{}
/* TODO 1 : END */
/*---------------------------------------*/
printf("init buffer\n");
return 0;
}
int attach_buffer(MessageBuffer **buffer) {
/*---------------------------------------*/
/* TODO 2 : attach buffer */
/* do not consider "no buffer situation" */
{}
/* TODO 2 : END */
/*---------------------------------------*/
printf("attach buffer\n");
printf("\n");
return 0;
}
int detach_buffer() {
if (shmdt(memory_segment) == -1) {
printf("shmdt error!\n\n");
return -1;
}
printf("detach buffer\n\n");
return 0;
}
int destroy_buffer() {
if(shmctl(shmid, IPC_RMID, NULL) == -1) {
printf("shmctl error!\n\n");
return -1;
}
printf("destroy shared_memory\n\n");
return 0;
}
int produce(MessageBuffer **buffer, int sender_id, char *data) {
if (is_full(**buffer)) {
printf("full!\n\n");
return -1;
}
if (strlen(data) > 100) {
printf("len(data) > 100\n\n");
return -1;
}
/*---------------------------------------*/
/* TODO 3 : produce message */
{}
/* TODO 3 : END */
/*---------------------------------------*/
printf("produce message\n");
return 0;
}
int consume(MessageBuffer **buffer, Message **message) {
if (is_empty(**buffer)) {
return -1;
}
/*---------------------------------------*/
/* TODO 4 : consume message */
{}
/* TODO 4 : END */
/*---------------------------------------*/
return 0;
}
int is_empty(MessageBuffer buffer) {
/*---------------------------------------*/
/* TODO 5 : is empty? */
{}
/* TODO 5 : END */
/*---------------------------------------*/
}
int is_full(MessageBuffer buffer) {
/*---------------------------------------*/
/* TODO 6 : is full? */
{}
/* TODO 6 : END */
/*---------------------------------------*/
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int daysOfMonths [12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int specialFebruary(int *y) {
if (* y % 100 == 0) {if (* y % 400 == 0) return 1; else return 0;}
else if (*y % 4 == 0) {return 1;}
else {return 0;}
}
void decrement_date(int *y, int *m, int *d) {
if (*d == 1 && *m == 1) {*d = 31; *m = 12; *y = *y - 1;}
else if (*d == 1) {*d = daysOfMonths [*m - 2]; *m = *m - 1;}
else {*d = *d - 1;}
printf("现在来到了前一天:%4d年%2d月%2d日\n", *y, *m, *d);
}
void increment_date(int *y, int *m, int *d) {
if (*d == 31 && *m == 12) {*d = 1; *m = 1; *y = *y + 1;}
else if (*d == daysOfMonths[*m - 1]) {*d = 1; *m = *m + 1;}
else {*d = *d + 1;}
printf("现在来到了后一天:%4d年%2d月%2d日\n", *y, *m, *d);
}
int main(void) {
srand((unsigned)time(NULL));
int y, m, d, go;
do {
printf("请输入一个年份:");
scanf("%d", &y);
if (y <= 0) {
printf("请输入公元元年以后的年份。\n");
}
} while (y <= 0);
if (specialFebruary(&y)) { daysOfMonths[1] ++;}
do {
printf("请输入一个月份:");
scanf("%d", &m);
if (m < 1 || m > 12) {
printf("请输入 1 到 12 的一个整数。\n");
}
} while (m < 1 || m > 12);
do {
printf("请输入一个日期:");
scanf("%d", &d);
if (d < 1 || d > daysOfMonths[m - 1]) {
if (m == 2) printf("%d 年的 ", y);
printf("%d 月没有 %d 日,请输入 1 到 %d 的一个整数。\n", m, d, daysOfMonths[m - 1]);
}
} while (d < 1 || d > daysOfMonths[m - 1]);
printf("您现在在%4d年%2d月%2d日,您想穿越到哪一天?\n 1. 前一天 0. 后一天\n请输入:", y, m, d);
scanf("%d", &go);
switch (go) {
case (0): {increment_date(&y, &m, &d);}; break;
case (1): {decrement_date(&y, &m, &d);}; break;
default: printf("让你乱输,现在哪都去不了了,留在%4d年%2d月%2d日吧!告辞~\n", y, m, d); break;
}
return 0;
}
|
C | /*
ETAPA 5 - TRABALHO DE COMPILADORES
Gabriel Zillmer e Rodrigo dal Ri
*/
#include <stdio.h>
#include <stdlib.h>
#include "tac.h"
TAC* tacCreate(int type, Hash_Node *res, Hash_Node *op1, Hash_Node *op2)
{
TAC *n = (TAC*) calloc(1, sizeof(TAC));
n->type = type;
n->res = res;
n->op1 = op1;
n->op2 = op2;
n->prev = 0;
n->next = 0;
return n;
}
TAC* tacJoin(TAC* l1, TAC* l2)
{
TAC* tac;
if(!l1) return l2;
if(!l2) return l1;
tac = l2;
while(tac->prev){
tac = tac->prev;
}
tac->prev = l1;
return l2;
}
void tacPrintBack(TAC *last)
{
fprintf(stderr, "\n ---Imprimindo codigo gerado---\n");
TAC *tac;
for(tac = last; tac; tac = tac->prev){
tacPrintOne(tac);
}
}
void tacPrintFoward(TAC* first)
{
fprintf(stderr, "\n ---Imprimindo codigo gerado---\n");
TAC *tac;
for(tac = first; tac; tac = tac->next){
tacPrintOne(tac);
}
}
TAC* tacReverse(TAC* tac)
{
TAC* t;
for(t = tac; t->prev; t = t->prev)
t->prev->next = t;
return t;
}
void tacPrintOne(TAC *tac)
{
if(tac->type == TAC_SYMBOL) return;
fprintf(stderr, "TAC(");
switch(tac->type){
case TAC_SYMBOL: fprintf(stderr, "TAC_SYMBOL"); break;
case TAC_ADD: fprintf(stderr, "TAC_ADD"); break;
case TAC_SUB: fprintf(stderr, "TAC_SUB"); break;
case TAC_MUL: fprintf(stderr, "TAC_MUL"); break;
case TAC_DIV: fprintf(stderr, "TAC_DIV"); break;
case TAC_L: fprintf(stderr, "TAC_L"); break;
case TAC_G: fprintf(stderr, "TAC_G"); break;
case TAC_LE: fprintf(stderr, "TAC_LE"); break;
case TAC_GE: fprintf(stderr, "TAC_GE"); break;
case TAC_EQ: fprintf(stderr, "TAC_EQ"); break;
case TAC_NE: fprintf(stderr, "TAC_NE"); break;
case TAC_AND: fprintf(stderr, "TAC_AND"); break;
case TAC_OR: fprintf(stderr, "TAC_OR"); break;
case TAC_NOT: fprintf(stderr, "TAC_NOT"); break;
case TAC_MOVE: fprintf(stderr, "TAC_MOVE"); break;
case TAC_READ: fprintf(stderr, "TAC_READ"); break;
case TAC_RET: fprintf(stderr, "TAC_RET"); break;
case TAC_IFZ: fprintf(stderr, "TAC_IFZ"); break;
case TAC_LABEL: fprintf(stderr, "TAC_LABEL"); break;
case TAC_JUMP: fprintf(stderr, "TAC_JUMP"); break;
case TAC_PRINT: fprintf(stderr, "TAC_PRINT"); break;
case TAC_PARPOP: fprintf(stderr, "TAC_PARPOP"); break;
case TAC_FUNCALL: fprintf(stderr, "TAC_FUNCALL"); break;
case TAC_BEGINFUN: fprintf(stderr, "TAC_BEGINFUN"); break;
case TAC_ENDFUN: fprintf(stderr, "TAC_ENDFUN"); break;
case TAC_AREAD: fprintf(stderr, "TAC_AREAD"); break;
case TAC_AWRITE: fprintf(stderr, "TAC_AWRITE"); break;
case TAC_AINIPUSH: fprintf(stderr, "TAC_AINIPUSH"); break;
case TAC_ASIZE: fprintf(stderr, "TAC_ASIZE"); break;
case TAC_PARPUSH: fprintf(stderr, "TAC_PARPUSH"); break;
default: fprintf(stderr, "TAC_UNKNOWN"); break;
}
if(tac->res) fprintf(stderr, ",%s", tac->res->text); else fprintf(stderr, ",0");
if(tac->op1) fprintf(stderr, ",%s", tac->op1->text); else fprintf(stderr, ",0");
if(tac->op2) fprintf(stderr, ",%s", tac->op2->text); else fprintf(stderr, ",0");
fprintf(stderr, ")\n");
}
TAC* tacGenerate(ASTREE *node)
{
int i = 0;
TAC *code[MAX_SONS];
TAC *result = 0;
if(!node) return 0;
for(i = 0; i < MAX_SONS; i++)
{
code[i] = tacGenerate(node->son[i]);
}
switch(node->type)
{
case ASTREE_SYMBOL: result = tacCreate(TAC_SYMBOL, node->symbol, 0, 0); break;
case ASTREE_ADD: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_ADD, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_SUB: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_SUB, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_MUL: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_MUL, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_DIV: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_DIV, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_L: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_L, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_G: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_G, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_LE: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_LE, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_GE: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_GE, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_EQ: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_EQ, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_NE: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_NE, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_AND: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_AND, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_OR: result = tacJoin(code[0],tacJoin(code[1],tacCreate(TAC_OR, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0))); break;
case ASTREE_NOT: result = tacJoin(tacJoin(code[0], code[1]),tacCreate(TAC_NOT, makeTemp(), code[0]?code[0]->res:0, code[1]?code[1]->res:0)); break;
case ASTREE_ATR: result = tacJoin(code[0], tacCreate(TAC_MOVE, node->symbol, code[0]?code[0]->res:0, 0)); break;
case ASTREE_READ: result = tacCreate(TAC_READ, node->symbol, 0, 0); break;
case ASTREE_RETURN: result = tacJoin(code[0], tacCreate(TAC_RET, node->symbol, code[0]?code[0]->res:0, 0)); break;
case ASTREE_IF: result = makeIfThenElse(code[0], code[1], 0); break;
case ASTREE_ELSE: result = makeIfThenElse(code[0], code[1], code[2]); break;
case ASTREE_WHILE: result = makeWhile(code[0], code[1]); break;
case ASTREE_PRINTL: result = tacJoin(tacCreate(TAC_PRINT, code[0]?code[0]->res:0, 0, 0), code[1]); break;
case ASTREE_FUNCALL: result = tacJoin(code[0], tacCreate(TAC_FUNCALL, makeTemp(), node->symbol, 0)); break;
case ASTREE_PARCALLL: result = tacJoin(code[1], tacCreate(TAC_PARPUSH, code[0]?code[0]->res:0, 0, 0)); break;
case ASTREE_FUNDEF: result = makeFunction(tacCreate(TAC_SYMBOL, node->symbol, 0, 0), code[1], code[2]); break;
case ASTREE_PARAM: result = tacCreate(TAC_PARPOP, node->symbol, 0, 0); break;
case ASTREE_PARL: result = tacJoin(code[0], code[1]); break;
//NÃO SEI SE PRECISA
case ASTREE_ARRAY_READ: result = tacCreate(TAC_AREAD, makeTemp(), node->symbol, code[0]?code[0]->res:0); break;
case ASTREE_ARRAY_WRITE: result = tacJoin(code[1], tacCreate(TAC_AWRITE, node->symbol, code[0]?code[0]->res:0, code[1]?code[1]->res:0)); break;
case ASTREE_VARINI: result = code[0]; break;
case ASTREE_INTL: result = tacJoin(code[0], tacCreate(TAC_AINIPUSH, node->symbol, 0, 0)); break;
case ASTREE_ARRINI: result = tacJoin(code[0], tacCreate(TAC_ASIZE, node->symbol, 0, 0)); break;
default: result = tacJoin(tacJoin(tacJoin(code[0], code[1]), code[2]), code[3]) ; break;
}
return result;
}
TAC* makeWhile(TAC* code0, TAC* code1)
{
TAC* whileTAC;
TAC *whileLabelTAC, *jumpLabelTAC;
Hash_Node *newWhileLabel = makeLabel(), *newJumpLabel = makeLabel();
TAC* jumpTAC = tacCreate(TAC_JUMP, newWhileLabel, 0, 0);
whileTAC = tacCreate(TAC_IFZ, newJumpLabel, code0?code0->res:0, 0);
whileLabelTAC = tacCreate(TAC_LABEL, newWhileLabel, 0, 0);
jumpLabelTAC = tacCreate(TAC_LABEL, newJumpLabel, 0, 0);
return tacJoin(tacJoin(tacJoin(tacJoin(tacJoin(whileLabelTAC, code0), whileTAC), code1),jumpTAC), jumpLabelTAC);
}
TAC* makeFunction(TAC* symbol, TAC* par, TAC* code)
{
return tacJoin(tacJoin(tacJoin( tacCreate(TAC_BEGINFUN, symbol->res, 0, 0), par) , code ), tacCreate(TAC_ENDFUN, symbol->res, 0, 0));
}
TAC* makeIfThenElse(TAC* code0, TAC* code1, TAC* code2)
{
TAC* ifTAC;
TAC* jumpTAC;
TAC* ifLabelTAC;
TAC* elseLabelTAC = 0;
Hash_Node* newIfLabel = makeLabel();
Hash_Node* newElseLabel = 0;
if(code2)
{
newElseLabel = makeLabel();
jumpTAC = tacCreate (TAC_JUMP, newElseLabel, 0, 0);
elseLabelTAC = tacCreate(TAC_LABEL, newElseLabel, 0, 0);
}
ifTAC = tacCreate(TAC_IFZ, newIfLabel, code0?code0->res:0, 0);
ifLabelTAC = tacCreate(TAC_LABEL, newIfLabel, 0, 0);
if(code2)
return tacJoin(tacJoin(tacJoin(tacJoin(tacJoin(tacJoin(code0, ifTAC), code1), jumpTAC),ifLabelTAC),code2), elseLabelTAC);
else
return tacJoin(tacJoin(tacJoin(code0, ifTAC), code1),ifLabelTAC);
}
|
C | #include<stdio.h>
#include<string.h>
int t,n,m,ans;
/***************************************************************/
//代码8-6 解决通配符问题的穷举搜索法
//返回通配符范式w与字符串s是否对应
//多传递两个变量表示字符串长度
int match(char *w,char *s,int len_w,int len_s){
//匹配w[pos]和s[pos]
int pos=0;
while(pos<len_w && pos<len_s && (w[pos]=='?'||w[pos]==s[pos]) )
++pos;
//无法再检索对应关系,则确认while循环结束
//已到达范式的最后一个字符的情况:字符串也到达了最后一个字符,则对应关系成立。
if(pos==len_w)
return pos==len_s;
//遇到"*"而结束的情况:利用递归调用,查看"*"对应几个字符
int skip;
if(w[pos]=='*')
for(skip=0;pos+skip<=len_s;skip++)
if(match(w+pos+1, s+pos+skip, len_w-pos-1, len_s-pos-skip))
return 1;
//除此之外的所有的对应关系都不成立
return 0;
}
/***************************************************************/
int main()
{
int i,j,k,l,len_w,len_s;
char w[111],s[111];
scanf("%d",&t);
while(t--){
scanf("%s%d",w,&n);
len_w=strlen(w);
while(n--){
scanf("%s",s);
len_s=strlen(s);
ans=match(w,s,len_w,len_s);
if(ans)
puts(s);
}
}
return 0;
}
/*
3
he?p
3
help
heap
helpp
*p*
3
help
papa
hello
*bb*
1
babbbc
//Answer//
help
heap
help
papa
babbbc
*/
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* export_support.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: molabhai <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/14 14:17:45 by molabhai #+# #+# */
/* Updated: 2021/04/14 14:17:50 by molabhai ### ########.fr */
/* */
/* ************************************************************************** */
#include "../minishell.h"
void filling_global(t_export *tmp)
{
int i;
i = 0;
g_global.export = malloc(sizeof(t_export));
if (!(g_global.export))
return ;
g_global.export->saver = ft_calloc(sizeof(char *),
arguments_in(tmp->saver, i) + 2);
if (!(g_global.export->saver))
return ;
while (tmp->saver[i])
{
g_global.export->saver[i] = ft_strdup(tmp->saver[i]);
i += 1;
}
}
t_export *filling_tmp(void)
{
t_export *tmp;
int i;
tmp = malloc(sizeof(t_export));
if (!(tmp))
return (NULL);
i = 0;
tmp->saver = ft_calloc(sizeof(char *),
arguments_in(g_global.export->saver, i) + 1);
if (!(tmp->saver))
return (NULL);
while (g_global.export->saver[i])
{
tmp->saver[i] = ft_strdup(g_global.export->saver[i]);
free(g_global.export->saver[i]);
i += 1;
}
free(g_global.export->saver);
free(g_global.export);
return (tmp);
}
int return_env_on(char *str)
{
int i;
char *s;
int on;
s = "env";
i = 0;
on = 0;
while (i < 3)
{
if (str[i] != s[i])
on = 1;
i += 1;
}
if (ft_isalpha(str[i]))
on = 1;
return (on);
}
t_export *check_export_init(char **splits, t_export *export)
{
int i;
i = 0;
if (export == NULL)
{
export = malloc(sizeof(t_export));
if (!(export))
return (NULL);
export->argument = ft_calloc(sizeof(char *),
arguments_in(splits, i) + 1);
if (!(export->argument))
return (NULL);
export->env = ft_calloc(sizeof(char *),
arguments_in(g_global.export->saver, i) + 1);
if (!(export->env))
return (NULL);
}
return (export);
}
char *split_reformulation(char *splits)
{
char *free_s;
splits = ft_strtrim(splits, "\t");
if (check_double_quote(splits) == 1
&& check_double_inside_single(splits) == 0)
{
free_s = splits;
splits = without_that(splits, '\"');
free(free_s);
}
else if (check_quote(splits) == 1
&& check_single_inside_double(splits) == 0)
{
free_s = splits;
splits = without_that(splits, '\'');
free(free_s);
}
return (splits);
}
|
C | /** This coder was programmed for dot-product of two vectors. **/
#include <stdio.h>
#include <stdlib.h>
/* Define length of dot product vectors */
#define VECLEN 100
int main (int argc, char* argv[])
{
int i,len=VECLEN;
double *a, *b;
double sum;
/* Assign storage for dot product vectors */
a = (double*) malloc (len*sizeof(double));
b = (double*) malloc (len*sizeof(double));
/* Initialize dot product vectors */
for (i=0; i<len; i++) {
a[i]=1.0;
b[i]=a[i];
}
/* Perform the dot product */
sum = 0.0;
for (i=0; i<len; i++)
{
sum += (a[i] * b[i]);
}
printf ("Done. Serial execution: sum = %f \n", sum);
free (a);
free (b);
}
|
C | /*******************************************************
判断奇偶
*******************************************************/
#include<stdio.h>
int main()
{
int a;
printf("请输入要判断的数\n");
scanf("%d",&a);
if(a%2==0)
printf("%d为偶数\n",a);
else
printf("%d为奇数\n",a);
}
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_5__ TYPE_2__ ;
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
typedef scalar_t__ ut64 ;
typedef int ut32 ;
struct TYPE_5__ {TYPE_1__* operands; } ;
struct TYPE_4__ {int immediate; } ;
typedef TYPE_2__ ArmOp ;
/* Variables and functions */
int UT32_MAX ;
int calcNegOffset (int,int) ;
__attribute__((used)) static ut32 bdot(ArmOp *op, ut64 addr, int k) {
ut32 data = UT32_MAX;
int n = 0;
int a = 0;
n = op->operands[0].immediate;
// I am sure there's a logical way to do negative offsets,
// but I was unable to find any sensible docs so I did my best
if (!(n & 0x3 || n > 0x7ffffff)) {
n -= addr;
data = k;
if (n < 0) {
n *= -1;
a = (n << 3) - 1;
data |= (0xff - a) << 24;
a = calcNegOffset(n, 5);
data |= a << 16;
a = calcNegOffset(n, 13);
data |= a << 8;
} else {
data |= (n & 31) << 27;
data |= (0xff & (n >> 5)) << 16;
data |= (0xff & (n >> 13)) << 8;
}
}
return data;
} |
C | /**
* Projekt: Implementace interpretu imperativního jazyka IFJ14
*/
/**
* @file memoryallocation2.c
* @author Antonin Cala(xcalaa00)
* @brief soubor obsahujici funkce pro spravu pameti
*/
#include "memoryallocation2.h"
#include "bst.h"
#include <stdlib.h>
#include <stdio.h>
#include "errors.h"
#include "globalvariables.h"
#include "symboltable.h"
/**
* @brief Makro pro volani inicializace jednotlivych struktur.
*/
#define initMemory(type, globalVariable, size, structType) \
\
structType * tmp = malloc(sizeof(structType) + (size) * sizeof(type));\
if (tmp == NULL)\
{\
errCode = ALLOCATION_ERROR;\
fatalError("Nepodarila se alokovat pamet.\n");\
}\
tmp -> firstFree = 0;\
tmp -> arraySize = size;\
tmp -> nextArr = globalVariable;\
globalVariable = tmp
void initDPLI(unsigned size)
{
initMemory(paramListItemT, dynamicPLIPtr, size, dynamicPLIT);
}
void initDCArr(unsigned size)
{
initMemory(char*, dynamicCharPtr, size, dynamicCharT);
}
void initDIArr(unsigned size)
{
initMemory(int, dynamicIntPtr, size, dynamicIntT);
}
void initDFArr(unsigned size)
{
initMemory(float, dynamicFloatPtr, size, dynamicFloatT);
}
void initDTASArr(unsigned size)
{
initMemory(threeAddressStackT, dynamicTASTPtr, size, dynamicTAST);
}
void initDVTArr(unsigned size)
{
initMemory(variableTableT, dynamicVTPtr, size, dynamicVTT);
}
void initDEArr (unsigned size)
{
initMemory(charList, dynamicElementPtr, size, dynamicElementT);
}
void initDElemArr(unsigned size)
{
initMemory(tElemT, dynamicElemPtr, size, dynamicElemT);
}
/**
* @brief Makro pro uvolneni pameti jednotlivych struktur.
*/
#define releaseMemory(globalVariable, structType) \
\
structType* lilHelper = globalVariable;\
while (lilHelper != NULL)\
{\
globalVariable = globalVariable -> nextArr;\
free(lilHelper);\
lilHelper = globalVariable;\
}
void releaseDPLI()
{
releaseMemory(dynamicPLIPtr, dynamicPLIT);
}
void releaseDChar()
{
releaseMemory(dynamicCharPtr, dynamicCharT);
}
void releaseDInt()
{
releaseMemory(dynamicIntPtr, dynamicIntT);
}
void releaseDFloat()
{
releaseMemory(dynamicFloatPtr, dynamicFloatT);
}
void releaseDTAS()
{
releaseMemory(dynamicTASTPtr, dynamicTAST);
}
void releaseDVT()
{
releaseMemory(dynamicVTPtr, dynamicVTT);
}
void releaseDElement()
{
releaseMemory(dynamicElementPtr, dynamicElementT);
}
void releaseDElem()
{
releaseMemory(dynamicElemPtr, dynamicElemT);
}
void releaseAll()
{
releaseDString();
releaseDTAC();
releaseDSTF();
releaseDSTV();
releaseDPLI();
releaseDChar();
releaseDFloat();
releaseDInt();
releaseDTAS();
releaseDVT();
releaseDElement();
releaseDElem();
releaseDOperList();
releaseDVariableInfo();
releaseDParameter();
releaseDSElem();
releaseDTElem();
if(source != NULL)
fclose(source);
}
/**
* @brief Makro na pridani dalsiho pole v pripade nedostatecneho mista v prechozich.
*/
#define addDynamic(size, globalVariable, structType, type)\
{\
structType *lilHelper = malloc(sizeof(structType) + size * sizeof(type));\
if (lilHelper == NULL)\
{\
errCode = ALLOCATION_ERROR;\
fatalError("Nepodarila se alokovat pamet.\n");\
}\
lilHelper -> nextArr = globalVariable;\
globalVariable = lilHelper;\
globalVariable -> arraySize = size;\
globalVariable -> firstFree = 0u;\
}
/**
* @brief makro na ziskani volneho prostoru daneho typu. Nahrazuje malloc.
*/
#define getDynamic(size, globalVariable, structType, Type)\
{\
if(size == 0u) return NULL;\
unsigned lilHelper = (globalVariable -> firstFree) + size - 1u;\
if (lilHelper < (globalVariable -> arraySize))\
{\
globalVariable -> firstFree = ((globalVariable -> firstFree) + size);\
return &(globalVariable -> Array[(globalVariable -> firstFree) - size]);\
}\
else\
{\
unsigned lilCounter = 2 * globalVariable -> arraySize;\
while (lilCounter < size)\
lilCounter = 2 * lilCounter;\
addDynamic(lilCounter, globalVariable, structType, Type);\
globalVariable -> firstFree = size;\
return &(globalVariable -> Array[(globalVariable -> firstFree) - size]);\
}\
}
paramListItemT* getDPLI(unsigned size)
{
getDynamic(size, dynamicPLIPtr, dynamicPLIT, paramListItemT);
}
char** getDChar(unsigned size)
{
getDynamic(size, dynamicCharPtr, dynamicCharT, char*);
}
int* getDInt(unsigned size)
{
getDynamic(size, dynamicIntPtr, dynamicIntT, int);
}
double* getDFloat(unsigned size)
{
getDynamic(size, dynamicFloatPtr, dynamicFloatT, double);
}
threeAddressStackT* getDTAS()
{
getDynamic(1u, dynamicTASTPtr, dynamicTAST, threeAddressStackT);
}
variableTableT* getDVT()
{
getDynamic(1u, dynamicVTPtr, dynamicVTT, variableTableT);
}
charList* getDElement()
{
getDynamic(1u, dynamicElementPtr, dynamicElementT, charList);
}
/**
* @brief Makro na uvolneni jednoho pole v pripade jeho prazdnosti.
*/
#define freeDynamic(globalVariable, structType)\
{\
structType *lilHelper = globalVariable;\
globalVariable = globalVariable -> nextArr;\
free(lilHelper);\
}
/**
* @brief Makro ktere uvolnuje misto v poli. Nahrazuje free.
*/
#define removeDynamic(size, globalVariable, structType)\
{\
unsigned lilSize = size;\
do{\
if (lilSize < (globalVariable -> firstFree))\
{\
globalVariable -> firstFree = (globalVariable -> firstFree) - lilSize;\
lilSize = 0u;\
}\
else\
{\
lilSize -= globalVariable -> firstFree;\
if(globalVariable -> nextArr == NULL)\
{ \
globalVariable -> firstFree = 0u;\
break;\
}\
else\
{\
freeDynamic(globalVariable, structType);\
globalVariable -> firstFree = (globalVariable -> firstFree)- lilSize;\
}\
}\
}while(lilSize != 0u);\
}
void removeDPLI(unsigned size)
{
removeDynamic(size, dynamicPLIPtr, dynamicPLIT);
}
void removeDChar(unsigned size)
{
removeDynamic(size, dynamicCharPtr, dynamicCharT);
}
void removeDInt(unsigned size)
{
removeDynamic(size, dynamicIntPtr, dynamicIntT);
}
void removeDFloat(unsigned size)
{
removeDynamic(size, dynamicFloatPtr, dynamicFloatT);
}
void removeDTAS(unsigned size)
{
removeDynamic(size, dynamicTASTPtr, dynamicTAST);
}
void removeDVT(unsigned size)
{
removeDynamic(size, dynamicVTPtr, dynamicVTT);
}
void removeDElement(unsigned size)
{
removeDynamic(size, dynamicElementPtr, dynamicElementT);
}
void removeDElem(unsigned size)
{
removeDynamic(size, dynamicElemPtr, dynamicElemT);
}
/**
* @brief Zjednoduseni jednotlivych volanic funkci.
*/
#define dynamicFunctions(type, globalVariable, structType, FName) \
\
void init ## FName(unsigned size) \
{ \
initMemory(type, globalVariable, size, structType); \
} \
\
void release ## FName() \
{ \
releaseMemory(globalVariable, structType); \
} \
\
void add ## FName(unsigned size) \
{ \
addDynamic(size, globalVariable, structType, type); \
} \
\
type* get ## FName(unsigned size) \
{ \
getDynamic(size, globalVariable, structType, type); \
} \
\
void free ## FName() \
{ \
freeDynamic(globalVariable, structType); \
} \
\
void remove ## FName(unsigned size) \
{ \
removeDynamic(size, globalVariable, structType); \
}
dynamicFunctions(operListT, dynamicOperListPtr, dynamicOperListT, DOperList)
dynamicFunctions(variableInfoT, dynamicVIPtr, dynamicVariableInfoT, DVariableInfo)
dynamicFunctions(parameterT, dynamicParameterPtr, dynamicParameterT, DParameter)
dynamicFunctions(sElemT, dynamicSElemPtr, dynamicSElemT, DSElem)
dynamicFunctions(tElemT, dynamicTElemPtr, dynamicTElemT, DTElem)
dynamicFunctions(threeAddressCodeT, staticMTACPtr, staticTACT, DTAC)
dynamicFunctions(STFunctionT, staticMSTFPtr, staticSTFT, DSTF)
dynamicFunctions(STVariableT, staticMSTVPtr, staticSTVT, DSTV)
dynamicFunctions(char, staticMSPtr, staticStringT, DString)
|
C | #include<stdio.h>
#include<stdlib.h>
struct Diagonal
{
int A[10];
int n; //size of the array
};
void set(struct Diagonal *m,int i,int j,int k)
{
if(i==j)
{
m->A[i-1]=k;
}
}
int get(struct Diagonal m, int i, int j)
{
if(i==j)
{
return m.A[i-1];
}
else
{
return 0;
}
}
void display(struct Diagonal m)
{
printf("\n");
int i,j;
for(i=0;i<m.n;i++)
{
for(j=0;j<m.n;j++)
{
if(i==j)
{
printf("%d ",m.A[i]);
}
else
{
printf("0 ");
}
}
printf("\n");
}
}
int main()
{
struct Diagonal m;
m.n=4;
set(&m,1,1,4);
set(&m,2,2,1);
set(&m,3,3,6);
set(&m,4,4,9);
printf("%d ",get(m,2,2));
display(m);
return 0;
}
|
C | #include<stdio.h>
void display(char , int , int );
int main(void)
{
int ch;
int rows, cols;
printf("Enter a character and two integers\n");
while((ch = getchar()) != '\n'){
scanf("%d%d",&rows,&cols);
getchar();
display(ch,rows,cols);
printf("Enter another character and two intgegers;\n");
printf("Enter a new line to quit.\n");
}
printf("Bye.\n");
return 0;
}
void display(char ch , int lines , int width )
{
int row ,col;
for(int row = 1; row <= lines ;row ++){
for(int col = 1 ; col <= width;col ++){
putchar(ch);
}
putchar('\n');
}
} |
C | /* program enum04.c */
main()
{
enum coin { penny,nickel,dime=4,quarter=6,half_dollar,dollar};
enum coin money;
for ( money=penny ; money<=dollar ; money++ )
printf("%3d",money);
printf("\n");
}
|
C | #include <stdio.h>
int fclose(FILE *stream)
{
int r = 0;
if (stream->_flags & _iowrite)
r = fflush(stream);
stream->_flags &= ~(_ioread | _iowrite);
return r;
}
|
C | /*
SST_File_POSIX.c
Author: Patrick Baggett <[email protected]>
Created: 12/23/2011
Purpose:
libsst-os file I/O for POSIX platforms
License:
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*/
#include "POSIXPrivate.h"
#include <SST/SST_File.h>
#include <SST/SST_Assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/******************************************************************************/
SST_File SST_OS_OpenFile(const char* path, uint32_t mode)
{
int flags;
int fd;
SST_File_POSIX* file;
mode_t openMode = 0;
SST_OS_DebugAssert(path != NULL, "File path may not be NULL");
/* Async I/O is not yet suppported */
if(mode & SST_OPEN_ASYNC)
return NULL;
/* Only one of SST_OPEN_HINTRAND or SST_OPEN_HINTSEQ may be set. */
if((mode & (SST_OPEN_HINTRAND|SST_OPEN_HINTSEQ)) == (SST_OPEN_HINTRAND|SST_OPEN_HINTSEQ))
return NULL;
switch(mode & 0xF) /* Lower byte has the open mode, remaining 24 bits are flags */
{
/* In each of the three cases (r/w/a), we set the execute bit so that memory mapped
I/O can specify 'execute' a permission too -- apparently the mapped view must be a
subset of the permissions the file was originally opened with. */
case SST_OPEN_READ:
flags = O_RDONLY;
break;
case SST_OPEN_WRITE:
flags = O_WRONLY | O_CREAT | O_TRUNC;
openMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH; /* User/Group: RW, Other: R */
break;
case SST_OPEN_APPEND:
flags = O_WRONLY | O_APPEND;
break;
/* Invalid open mode */
default:
return NULL;
}
fd = open(path, flags, openMode);
if(fd < 0)
return NULL;
#if _XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L
if(mode & SST_OPEN_HINTRAND)
posix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM);
else if(mode & SST_OPEN_HINTSEQ)
posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
#endif
file = (SST_File_POSIX*)malloc(sizeof(SST_File_POSIX));
if(file == NULL)
{
close(fd);
return NULL;
}
file->fd = fd;
file->isAsync = (int)(mode & SST_OPEN_ASYNC); /* Not yet used */
#ifdef _DEBUG
file->nrMmaps = 0;
#endif
return (SST_File)file;
}
/******************************************************************************/
uint64_t SST_OS_WriteFile(SST_File file, const void* buf, uint64_t bytes)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
uint64_t bytesLeft = bytes;
uint64_t totalWritten;
const char* writePtr = (const char*)buf;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
SST_OS_DebugAssert(buf != NULL, "Buffer may not be NULL");
SST_OS_DebugAssert(!fp->isAsync, "Files opened for asynchronous I/O may not use the synchronous file I/O functions");
#ifdef _DEBUG
SST_OS_DebugAssert(fp->nrMmaps == 0, "Cannot use synchronous file I/O while memory maps exist!");
#endif
/* Do nothing? */
if(bytes == 0)
return 0;
totalWritten = 0;
do
{
size_t nrBytesToWrite;
ssize_t nrWritten;
/* Determine how many bytes to write */
if(bytesLeft > SIZE_MAX)
nrBytesToWrite = SIZE_MAX;
else
nrBytesToWrite = (size_t)bytesLeft;
/* Actually write data to the file */
nrWritten = write(fp->fd, writePtr, nrBytesToWrite);
if(nrWritten < 0) /* error */
{
/* OK, but some of the data may have been written, so stop now but return how far we did get */
break;
}
/* Advance pointers and counters */
writePtr += nrWritten;
totalWritten += (uint64_t)nrWritten;
bytesLeft -= (uint64_t)nrWritten;
} while(bytesLeft > 0);
return totalWritten;
}
/******************************************************************************/
uint64_t SST_OS_ReadFile(SST_File file, void* buf, uint64_t bytes)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
uint64_t bytesLeft = bytes;
uint64_t totalRead;
char* readPtr = (char*)buf;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
SST_OS_DebugAssert(buf != NULL, "Buffer may not be NULL");
SST_OS_DebugAssert(!fp->isAsync, "Files opened for asynchronous I/O may not use the synchronous file I/O functions");
#ifdef _DEBUG
SST_OS_DebugAssert(fp->nrMmaps == 0, "Cannot use synchronous file I/O while memory maps exist!");
#endif
/* Do nothing? */
if(bytes == 0)
return 0;
totalRead = 0;
do
{
size_t nrBytesToRead;
ssize_t nrRead;
/* Determine how many bytes to read */
if(bytesLeft > SIZE_MAX)
nrBytesToRead = SIZE_MAX;
else
nrBytesToRead = (size_t)bytesLeft;
nrRead = read(fp->fd, readPtr, nrBytesToRead);
if(nrRead <= 0)
{
/* Error or EOF, but some of the reads could have succeeded, so return how much
was read */
break;
}
/* Advance pointers and counters */
readPtr += nrRead;
totalRead += (uint64_t)nrRead;
bytesLeft -= (uint64_t)nrRead;
} while(bytesLeft > 0);
return totalRead;
}
/******************************************************************************/
int SST_OS_GetFilePointer(SST_File file, uint64_t* fpReturn)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
off_t off;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
SST_OS_DebugAssert(fpReturn != NULL, "File pointer return may not be NULL");
#ifdef _DEBUG
SST_OS_DebugAssert(fp->nrMmaps == 0, "Cannot use synchronous file I/O while memory maps exist!");
#endif
off = lseek(fp->fd, 0, SEEK_CUR);
if(off == (off_t)-1)
return 0;
*fpReturn = (uint64_t)off;
return 1;
}
/******************************************************************************/
int SST_OS_SetFilePointer(SST_File file, uint64_t ptr)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
off_t off;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
#ifdef _DEBUG
SST_OS_DebugAssert(fp->nrMmaps == 0, "Cannot use synchronous file I/O while memory maps exist!");
#endif
/* Trying to seek > 4GB but underlying OS doesn't support it -> error */
if(sizeof(off_t) == sizeof(uint32_t) && ptr > UINT32_MAX)
return 0;
off = (off_t)ptr;
if(lseek(fp->fd, off, SEEK_SET) != (off_t)-1)
return 0;
return 1;
}
/******************************************************************************/
int SST_OS_FileEOF(SST_File file)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
off_t here, eof;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
#ifdef _DEBUG
SST_OS_DebugAssert(fp->nrMmaps == 0, "Cannot use synchronous file I/O while memory maps exist!");
#endif
/* Step 1: Get current file position */
here = lseek(fp->fd, 0, SEEK_CUR);
if(here == (off_t)-1)
return -1;
/* Step 2: Seek to EOF */
eof = lseek(fp->fd, 0, SEEK_END);
if(eof == (off_t)-1)
return -2;
/* Step 3: Put it back! */
lseek(fp->fd, here, SEEK_SET);
/* Step 4: Compare and return */
return (here == eof);
}
/******************************************************************************/
void SST_OS_FlushFile(SST_File file)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
(void)fsync(fp->fd);
}
/******************************************************************************/
void SST_OS_CloseFile(SST_File file)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
if(fp->fd > 0)
{
close(fp->fd);
#ifdef _DEBUG
fp->fd = 0;
#endif
}
#ifdef _DEBUG
SST_OS_DebugAssert(fp->nrMmaps == 0, "Closing file with open memory maps means leaked OS resources");
#endif
free(fp);
}
/******************************************************************************/
int SST_OS_SeekFile(SST_File file, int64_t offset, int fromWhere)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
int method;
off_t off;
SST_OS_DebugAssert(file != NULL, "File handle may not be NULL");
#ifdef _DEBUG
SST_OS_DebugAssert(fp->nrMmaps == 0, "Cannot use synchronous file I/O while memory maps exist!");
#endif
off = (off_t)offset;
/* Map SST to POSIX constants (pretty sure they are isomorphic) */
switch(fromWhere)
{
case SST_SEEK_START: method = SEEK_SET; break;
case SST_SEEK_CUR: method = SEEK_CUR; break;
case SST_SEEK_END: method = SEEK_END; break;
/* Invalid parameter */
default: return 0;
}
if(lseek(fp->fd, off, method) == (off_t)-1)
return 0;
return 1;
}
/******************************************************************************/
uint64_t SST_OS_GetFileSize(SST_File file)
{
SST_File_POSIX* fp = (SST_File_POSIX*)file;
struct stat info;
if(fstat(fp->fd, &info) == 0) /* i.e. success */
return (uint64_t)info.st_size;
/* Failure */
return UINT64_MAX;
}
/******************************************************************************/
|
C | /* findlm.c Daniel Scharstein 6/16/99 */
/* driver for landmark program
*/
static char rcsid[] = "$Id: findlm.c 6071 2015-10-16 21:58:31Z carrick $";
#include <stdio.h>
#include <math.h>
#include "image.h"
#include "landmark.h"
static char usage[] = "\n\
usage: %s [options] img.pgm\n\
\n\
search for landmark in img.pgm\n\
\n\
OPTIONS DEFAULTS\n\
-f factor self-similarity factor %g\n\
-s spacing spacing of scanlines to search %d\n\
-w window size of search window %d\n\
-t threshold threshold for match %d\n\
-p peak width max peakw at .5 max (percent of window) %d\n\
-h hold number of pixels to skip %d\n\
-y ycoord search single scanline at ycoord -\n\
-x draw X at match (line otherwise) \n\
-v verbose \n\
\n\
good params for -f 2: -t 40, -p 6 \n\
ok params for -f 4: -t 20, -p 6 \n\
";
int main(int argc, char **argv)
{
int o, i;
GrayImage im1;
char *im1name;
landmarks lamarr;
double factor = FACTOR_DEFAULT;
int spacing = SPACING_DEFAULT;
int window = WINDOW_DEFAULT;
int threshold = THRESHOLD_DEFAULT;
int peakperc = PEAKW_PERCENT;
int skip = SKIP_DEFAULT;
int ycoord = -1;
int drawX = 0;
int verbose = 0;
int peakw;
while ((o = getopt(argc, argv, "f:s:w:t:p:h:y:xv")) != -1)
switch (o) {
case 'f': factor = atof(optarg); break;
case 's': spacing = atoi(optarg); break;
case 'w': window = atoi(optarg); break;
case 't': threshold = atoi(optarg); break;
case 'p': peakperc = atoi(optarg); break;
case 'h': skip = atoi(optarg); break;
case 'y': ycoord = atoi(optarg); /* fall through to drawX=1 */
case 'x': drawX = 1; break;
case 'v': verbose = 1; break;
default:
fprintf(stderr, "Unrecognized option %c\n", o);
}
if (optind >= argc) {
fprintf(stderr, usage, argv[0], FACTOR_DEFAULT,
SPACING_DEFAULT, WINDOW_DEFAULT, THRESHOLD_DEFAULT,
PEAKW_DEFAULT, SKIP_DEFAULT);
exit(1);
}
im1name = argv[optind];
im1 = (GrayImage)imLoad(IMAGE_GRAY, im1name);
if (im1 == (GrayImage)NULL) {
fprintf(stderr, "can't load image %s\n", im1name); exit(1); }
peakw = (peakperc * window) / 100 + PEAKW_ADD;
lamarr = landmarkParams(im1, "out.match.ppm", verbose, drawX,
window, peakw, threshold,
factor, spacing, skip, ycoord);
for (i=0; i<lamarr.count; i++) {
landm lam = lamarr.lm[i];
fprintf(stderr, "found at %3d,%3d to %d,%d - code = %d\n",
lam.xtop, lam.ytop, lam.xbottom, lam.ybottom, lam.code);
}
assert(rcsid); /* to avoid warning message */
return(0);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/*
* p2p聊天程序客户端
* 父进程发送数据
* 子进程接收数据
* */
#define ERROR_EXIT() {\
printf("errno:%d\n",errno);\
perror("error");\
exit(EXIT_FAILURE);\
}
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
ERROR_EXIT();
}
struct sockaddr_in srvaddr;
srvaddr.sin_family = AF_INET;
srvaddr.sin_port = htons(8001);
srvaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sockfd, (struct sockaddr *)&srvaddr, sizeof(struct sockaddr)) == -1) {
ERROR_EXIT();
}
pid_t pid = fork();
if (pid > 0) {
char sendbuf[1024] = {0};
while(fgets(sendbuf, sizeof(sendbuf), stdin) != NULL) {
int cnt = write(sockfd, sendbuf, sizeof(sendbuf));
if (cnt == -1) {
ERROR_EXIT();
}
memset(sendbuf, 0, sizeof(sendbuf));
}
} else if (pid == 0) {
char recvbuf[1024] = {0};
while(1) {
int ret = read(sockfd, recvbuf, sizeof(recvbuf));
if (ret == -1) {
ERROR_EXIT();
}
fputs(recvbuf, stdout);
memset(recvbuf, 0, sizeof(recvbuf));
}
}
else {
ERROR_EXIT();
}
close(sockfd);
return 0;
}
|
C | #include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
int x = 1; // El caballo inica en la casilla superior
int y = 1; // izquierda
const int TAMANO = 8; // Cambiar esta variable para resolver el problema del
// recorrido del caballo en un tablero de N * N
int contador = 1; // Esta variable lleva la cuenta de las casillas
// recorridas
int ciclos = 0; // Esta variable cuenta los ciclos que se intentan
// antes de terminar que ya no haya lugares a los cuales
// ir
int intentos_fallidos = 0; // Esta variable cuenta cuantos ciclos se
// intentan antes de obtener el que pidio el usuario.
// Prototipo de funcion Imprime
void Imprime( int a[TAMANO + 1][TAMANO + 1]);
int main()
{ // Abre main
srand(time(NULL));
int Arreglo[TAMANO + 1][TAMANO + 1];
Arreglo[y][x] = 1;
int dado1;
int dado2;
int casillas_requeridas = 0;
do
{ // Abre while
printf("\nCuantas casillas quiere que recorra por lo menos?");
printf("\n(Un numero positivo menor o igual que %d): ", TAMANO*TAMANO );
scanf("%d", &casillas_requeridas);
} while ((TAMANO*TAMANO < casillas_requeridas) || (0 > casillas_requeridas));
clock_t begin = clock();
while ( contador < casillas_requeridas )
{ // Abre while
intentos_fallidos++; // Se incrementa cada que inica un intento de
// completar las casillas pedidas por el usuario
contador = 1; // Dado que ya se ha colocado al caballo en (y,X), se
// inicia el contador en 1
int ciclos = 0; // Se inicia con 0 ciclos o lanzamientos de dados infructuosos
// Cada vez que se aborta un intento han de limpiarse las casillas, con
// el siguiente par de ciclos se establecen a 0 nuevamente.
int s;
int t;
for ( s = 0; s <= TAMANO; s++ )
{ // Abre for
for ( t = 0; t <= TAMANO; t++ )
Arreglo[s][t] = 0;
} // Cierra for
// Se ha de colocar el caballo en la esquina superior izquierda cada vez
// Desde luego se puede poner en cualquier parte
x = 1;
y = 1;
Arreglo[y][x] = 1;
// Mientras no se encuentre un lugar para el caballo
while ( 1000 != ciclos )
// Por que 100? En el caso extremo en el que solo falte una casilla por
// llenar (la 64 para un tablero de 8*8) la mayoria de las casillas aleatorias
// estaran ya ocupadas, pero a la larga, una de cada 64 (TAMANO*TAMANO) sera
// la correcta. Para evitar que el intento se aborte debido a una fluctuacion
// estadistica (por ejemplo que de 500 casillas aleatorias ninguna sea la
// casilla en blanco) se pone un "colchon" de 1000 casillas. Esto se puede
// cambiar, desde luego, teniendo en cuenta cual es la probabilidad de que se
// obtenga una casilla cualquiera.
{ // Abre while
ciclos++;
dado1 = 1 + rand() % TAMANO;
dado2 = 1 + rand() % TAMANO;
if ( 2 == fabs(x - dado1))
{ // Abre if
if ( 1 == fabs(y - dado2))
if ( 0 == Arreglo[dado1][dado2] )
{ // Abre if
Arreglo[dado1][dado2] = ++contador;
x = dado1;
y = dado2;
ciclos = 0;
} // Cierra if
} // Cierra if
if ( fabs(fabs(x) - fabs(dado1)) == 1)
{ // abre if
if ( fabs(fabs(y) - fabs(dado2)) == 2 )
if ( 0 == Arreglo[dado1][dado2] )
{ // Abre if
Arreglo[dado1][dado2] = ++contador;
x = dado1;
y = dado2;
ciclos = 0;
} // Cierra if
} // Cierra if
} // Cierra while
} // Cierra while
printf("\nLISTO!\n");
printf("\nSe recorrieron %d casillas\n", contador);
printf("\nSe intentaron %d circuitos antes de obtener", intentos_fallidos);
printf(" el requerido.\n");
Imprime( Arreglo);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("time: %lf\n",time_spent);
} // Cierra main
/*La funcion siguiente despliega el tablero de ajedrez */
//////////////////////////////////////////
// Imprime
///////////////////////////////////////////
void Imprime( int Matriz[TAMANO + 1][TAMANO + 1])
{ // Abre la funcion Imprimir
int i;
int j;
printf("\n\nEste es el tablero:\n\n ");
for ( i = 1; i <= TAMANO; i++ )
{ // Abre for
for ( j = 1; j <= TAMANO; j++)
{ // abre for anidado
printf(" %d\t", Matriz[i][j]);
} // Cierra for anidado
printf("\n\n\n");
} // Cierra for
printf("\n\n\n");
} // Cierra la funcion Imprimir
|
C | // ganchan.c
// by Find.
inherit SKILL;
string *dodge_msg = ({
"ֻ$n˫ɶٿԱһ$Nʽȫա\n",
"$nһʽơ˲ѲӰ\n",
"$n˫һţתƮ֮߳⣬$Nʽ$n˿\n",
"ֻ$nһšߣ$Nзա\n"
});
int valid_enable(string usage)
{
return (usage == "dodge") || (usage == "move");
}
int valid_learn(object me) { return 1; }
string query_dodge_msg(string limb)
{
return dodge_msg[random(sizeof(dodge_msg))];
}
int effective_level() { return 12;}
int practice_skill(object me)
{
if( (int)me->query("kee") < 40 )
return notify_fail("̫ˣϰ˲ϲ\n");
me->receive_damage("kee", 30, "tire");
return 1;
}
/* ˺ֵԽСԽԽԽ0 ΪѶȡ*/
int practice_bonus()
{
return -50;
}
/* ˺ֵԽСԽѧԽԽѧ0 ΪѶȡ*/
int learn_bonus()
{
return -20;
}
/* 书С 75 ʱ˺ֵԽСѧԽ졣
* 书 75 ʱ˺ֵԽѧԽ졣
* 书 75 ʱ˺ֵû塣
* Ҳ˵˺ֵСڳѧϰԽѧԽ
* ֵѧϰѣԽѧԽ
* ֵΪǰѶûб仯
*/
int black_white_ness()
{
return -20;
}
|
C | #include <stdio.h>
int gcd(int,int);
int gdc(int u, int v){
if(v==0){
printf("Reached base case. Returning.\n");
return;
}
else{
printf("calling gcd: gcd(%d,%d)\n",v,(u%v));
return gcd(v,(u%v));
}
}
int main(void){
int x=0,y=0;
scanf("%d%d",&x,&y);
printf("%d\n", gcd(x,y));
return 0;
}
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ tree ;
/* Variables and functions */
int /*<<< orphan*/ CHREC_LEFT (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ CHREC_RIGHT (int /*<<< orphan*/ ) ;
unsigned int CHREC_VARIABLE (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ NULL_TREE ;
#define POLYNOMIAL_CHREC 128
int const TREE_CODE (int /*<<< orphan*/ ) ;
scalar_t__ automatically_generated_chrec_p (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ build_polynomial_chrec (unsigned int,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
__attribute__((used)) static tree
chrec_component_in_loop_num (tree chrec,
unsigned loop_num,
bool right)
{
tree component;
if (automatically_generated_chrec_p (chrec))
return chrec;
switch (TREE_CODE (chrec))
{
case POLYNOMIAL_CHREC:
if (CHREC_VARIABLE (chrec) == loop_num)
{
if (right)
component = CHREC_RIGHT (chrec);
else
component = CHREC_LEFT (chrec);
if (TREE_CODE (CHREC_LEFT (chrec)) != POLYNOMIAL_CHREC
|| CHREC_VARIABLE (CHREC_LEFT (chrec)) != CHREC_VARIABLE (chrec))
return component;
else
return build_polynomial_chrec
(loop_num,
chrec_component_in_loop_num (CHREC_LEFT (chrec),
loop_num,
right),
component);
}
else if (CHREC_VARIABLE (chrec) < loop_num)
/* There is no evolution part in this loop. */
return NULL_TREE;
else
return chrec_component_in_loop_num (CHREC_LEFT (chrec),
loop_num,
right);
default:
if (right)
return NULL_TREE;
else
return chrec;
}
} |
C | #include "q.h"
int main()
{
char a,*p = "hello";
struct queue *q;
q = queue_create(20);
while(*p)
{
enqueue(q,*p);
p++;
}
while(!queue_is_empty(q))
{
dequeue(q,&a);
printf("%c ",a);
}
printf("\n");
return 0;
}
|
C | #include <unistd.h>
#include <signal.h>
#define SECOND 1
void do_nothing();
void do_int();
main ()
{
int i;
unsigned sec = 1;
signal(SIGINT, do_int);
for (i = 1; i < 8; i++) {
alarm(sec);
signal(SIGALRM, do_nothing);
printf("%d varakozik, meddig?\n", i);
pause();
}
}
void do_nothing(){ ;}
void do_int() {
printf("int erkezett");
signal(SIGINT,SIG_IGN);
} |
C | #include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#include <stdio.h>
#define B_PORT 22160
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sock, length, n;
socklen_t fromlen;
struct sockaddr_in server;
struct sockaddr_in from;
char buf[1024];
char value[10];
float bar;
//********************************UDP******************************************************
//This part is modified from http://www.linuxhowtos.org/data/6/server_udp.c
sock=socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("Opening socket");
length = sizeof(server);
bzero(&server,length);
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(B_PORT);
if (bind(sock,(struct sockaddr *)&server,length)<0)
error("binding");
fromlen = sizeof(struct sockaddr_in);
printf("The Server B is up and running using UDP on port %d.\n",htons(server.sin_port));
while(1)
{
//-------------------------------receive the value and do the computation x*x*x----------------
n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen);
if (n < 0) error("recvfrom");
strcpy(value, buf);
bar=atof(value);
printf("The Server B received input <%g>\n", bar);
bar=bar*bar*bar; // X to the power of 2
printf("The Server B calculated cube: <%g>\n", bar);
sprintf(value,"%g",bar);
//------------------------------send back to AWS---------------------------------------------
n = sendto(sock,value,sizeof(value),
0,(struct sockaddr *)&from,fromlen);
if (n < 0) error("sendto");
printf("The Server B finished sending the output to AWS\n");
bzero(buf,1024);
}
return 0;
}
|
C |
#include <stdio.h>
FILE *in_fptr,
*fopen();
char matrix[16][16]; /* matrix[0][] and matrix [][0] are not used */
/* so that the subscripts will be 1-15 (to */
/* make the code simpler) */
int data_set_count, matrix_size;
/* ******************************************************** */
main()
{
void process_one_matrix();
if ( (in_fptr = fopen("symm.in", "r")) == NULL )
{
printf("*** can't open input file *** \n");
exit();
}
data_set_count = 0;
fscanf(in_fptr, "%d\n", &matrix_size);
while ( matrix_size > 0 )
{/* process one matrix */
++data_set_count;
process_one_matrix();
fscanf(in_fptr, "%d\n", &matrix_size);
}/* end while ( more input ) */
if ( fclose(in_fptr) == EOF )
{
printf("*** can't close input file *** \n");
exit();
}
}/* end main */
/* ******************************************************** */
void process_one_matrix()
{
int r, c, request_count, diag, j;
char space_or_newline;
void prnt_diag();
/* read and print the matrix */
printf("Input matrix #%d:\n", data_set_count);
for ( r = 1; r <= matrix_size; ++r )
for ( c = 1; c <= matrix_size; ++c )
{
fscanf(in_fptr, "%c%c", &matrix[r][c], &space_or_newline);
printf("%c%c", matrix[r][c], space_or_newline);
}
/* read and process the diagonal requests for this matrix */
fscanf(in_fptr, "%d\n", &request_count);
for ( j = 1; j <= request_count; ++j )
{
fscanf(in_fptr, "%d", &diag);
printf("Symmetric diagonals %d:\n", diag);
prnt_diag(1,diag); /* print upper diagonal */
if ( diag > 1 )
prnt_diag(diag,1); /* print lower diagonal */
}/* end for */
printf("\n");
}/* end process_one_matrix */
/* ******************************************************** */
void prnt_diag(int start_row, int start_col)
{
int r, c;
for ( r = start_row, c = start_col;
r <= matrix_size && c <= matrix_size; ++r, ++c )
{
if ( r > start_row )
/* need a space before the 2nd char, 3rd char, etc. */
printf(" ");
printf("%c", matrix[r][c]);
}
printf("\n");
}/* end prnt_diag */
/* ******************************************************** */
|
C |
void f1(int n,int a[100][100])
{
int i;
for(i=0;i<=n-1;i++)
{
int x=a[i][0],j;
for(j=1;j<=n-1;j++)
if(x>a[i][j]) x=a[i][j];
if(x>0)
for(j=0;j<=n-1;j++)
a[i][j]-=x;
}
for(i=0;i<=n-1;i++)
{
int x=a[0][i],j;
for(j=1;j<=n-1;j++)
if(x>a[j][i]) x=a[j][i];
if(x>0)
for(j=0;j<=n-1;j++)
a[j][i]-=x;
}
}
void f2(int n,int a[100][100])
{
int i,j;
for(i=1;i<=n-2;i++)
{
a[0][i]=a[0][i+1];
a[i][0]=a[i+1][0];
}
for(i=1;i<=n-2;i++)
for(j=1;j<=n-2;j++)
a[i][j]=a[i+1][j+1];
}
int loop(int n,int a[100][100])
{
f1(n,a);
int x=a[1][1];
if(n==2) return a[1][1];
else
{
f2(n,a);
return x+loop(n-1,a);
}
}
void main(void)
{
int t,n;
scanf("%d",&n);
for(t=1;t<=n;t++)
{
int a[100][100],i,j;
for(i=0;i<=n-1;i++)
for(j=0;j<=n-1;j++)
scanf("%d",&a[i][j]);
printf("%d\n",loop(n,a));
}
} |
C | #include<stdio.h>
typedef unsigned long long ull;
int main()
{
int t;
ull a,b,temp1,i,j,sum,sum1,sum2;
scanf("%d",&t);
while(t--)
{
sum=0;
scanf("%llu%llu",&a,&b);
j=a;
sum1=sum2=0;
while(a<b&&a%10!=0){
j=a; sum1=0;
while(j>0)
{
temp1=j%10;
if(temp1%2==0)
sum1=sum1+2*j;
else
sum1=sum1+j;
j=j/10;
}
sum=sum+(sum1%10);
a++;
}
while(a<b&&b%10!=0){
j=b; sum1=0;
while(j>0)
{
temp1=j%10;
if(temp1%2==0)
sum1=sum1+2*j;
else
sum1=sum1+j;
j=j/10;
}
sum=sum+(sum1%10);
//printf("%d %d\n",a,b);
b--;
}
j=b; sum1=0;
while(j>0)
{
temp1=j%10;
if(temp1%2==0)
sum1=sum1+2*j;
else
sum1=sum1+j;
j=j/10;
}
sum=sum+(sum1%10);
if(b>=a)
sum+=((b-a)/10)*45;
printf("%llu\n",sum);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "commands.h"
#include "utils.h"
static void release_argv(int argc, char*** argv);
int main()
{
char buf[8096];
int argc;
char** argv;
while (1) {
fgets(buf, 8096, stdin);
// printf("parse start\n");
mysh_parse_command(buf, &argc, &argv);
// printf("argc : %d\n", argc);
// printf("parse end\nargv[0] : %s\n", argv[0]);
if (strcmp(argv[0], "") == 0) {
printf("if no.1 excuted\n");
goto release_and_continue;
} else if (strcmp(argv[0], "cd") == 0) {
printf("if no.2 excuted\n");
if (do_cd(argc, argv)) {
fprintf(stderr, "cd: Invalid arguments\n");
}
} else if (strcmp(argv[0], "pwd") == 0) {
printf("if no.3 excuted\n");
if (do_pwd(argc, argv)) {
fprintf(stderr, "pwd: Invalid arguments\n");
}
} else if (strcmp(argv[0], "exit") == 0) {
printf("exit excuted\n");
goto release_and_exit;
} else {
fprintf(stderr, "%s: command not found\n", argv[0]);
}
release_and_continue:
release_argv(argc, &argv);
printf("realse done\n");
continue;
release_and_exit:
release_argv(argc, &argv);
break;
}
return 0;
}
static void release_argv(int argc, char*** argv) {
for (int i = 0; i < argc; ++i) {
free((*argv)[i]);
}
free(*argv);
*argv = NULL;
}
|
C |
/* Inclusiones */
#include <avr/io.h>
#include <stdint.h>
#include <util/delay.h>
/* Constantes y macros */
#define DDR_SERIAL_TX DDRD
#define PORT_SERIAL_TX PORTD
#define SERIAL_TX 1
#define BIT_DURATION_US 417
/* Variables globales */
/* Declaraci�n de funciones */
void Serial_Tx_Byte(char byte);
void Serial_Tx_String(char *str);
void Serial_Tx_Integer(int32_t num);
/* Funci�n principal */
int main(void){
uint8_t num_01 = 123;
int16_t num_02 = -350;
int32_t num_03 = 0;
/* Configurar el pin de transmisi�n como salida digital */
DDR_SERIAL_TX |= (1 << SERIAL_TX);
/* Inicializar el pin en ALTO */
PORT_SERIAL_TX |= (1 << SERIAL_TX);
/* Transmitir un texto indefinidamente */
while(1){
Serial_Tx_String("Numero 01:");
Serial_Tx_Integer((int32_t)num_01);
Serial_Tx_String("\n\r");
_delay_ms(1000);
Serial_Tx_String("Numero 02:");
Serial_Tx_Integer((int32_t)num_02);
Serial_Tx_String("\n\r");
_delay_ms(1000);
Serial_Tx_String("Numero 03:");
Serial_Tx_Integer(num_03);
Serial_Tx_String("\n\r");
_delay_ms(1000);
}
return 0;
}
/* Definici�n de funciones */
void Serial_Tx_Byte(char byte){
int8_t bit_pos;
/* Transmitir el bit de inicio (en BAJO) */
PORT_SERIAL_TX &= ~(1 << SERIAL_TX);
_delay_us(BIT_DURATION_US);
/* Transmitir los bits de datos */
for(bit_pos = 0; bit_pos < 8; bit_pos++){
// Si el bit en la posici�n correspondiente es '1' ...
if(byte & (1 << bit_pos)){
// Colocar el pin de transmisi�n en ALTO
PORT_SERIAL_TX |= (1 << SERIAL_TX);
// De lo contrario ...
}else{
// Colocar el pin de transmisi�n en BAJO
PORT_SERIAL_TX &= ~(1 << SERIAL_TX);
}
/* Esperar un tiempo equivalente a la duraci�n del bit */
_delay_us(BIT_DURATION_US);
}
/* Transmitir el bit de parada (en ALTO) */
PORT_SERIAL_TX |= (1 << SERIAL_TX);
_delay_us(BIT_DURATION_US);
}
void Serial_Tx_String(char *str){
/* Mientras no se alcance el final de la cadena */
while(*str != '\0'){
/* Transmitir el caracter correspondiente */
Serial_Tx_Byte(*str);
/* Incrementar el valor del puntero (apuntar al siguiente caracter
en el arreglo) */
str++;
}
}
void Serial_Tx_Integer(int32_t num){
char signo_y_digitos[12];
uint8_t signo = 0;
int32_t digito;
int8_t indice = 11;
/* Determinar el signo del n�mero */
if(num < 0){
signo = 1;
num = -num;
}
/* Indicar el fin de la cadena de caracteres */
signo_y_digitos[indice--] = '\0';
/* Extraer los d�gitos uno a uno, empezando por las unidades */
do{
digito = (num % 10) + '0';
signo_y_digitos[indice--] = (char)digito;
num /= 10;
}while(num != 0);
/* Agregar el signo (de ser necesario) */
if(signo){
signo_y_digitos[indice] = '-';
}else{
indice++;
}
/* Transmitir el n�mero */
Serial_Tx_String(&signo_y_digitos[indice]);
}
|
C | /*
* Exercise 6.4
* Write a program that calculates the average of an array of 10 floating-point
* values.
*/
#include <stdio.h>
int main ()
{
/* declare a float accumlator s, initialized to 0, and an array of 10
* floats initialized to some random float numbers */
float s = 0, arr[10] = {67.39, 47.28, 22.30, 87.71, 12.14, 91.31, 23.27,
75.20, 52.45, 98.18};
/* calculate the sum */
int i;
for (i = 0; i < 10; s += arr[i++]);
/* print the mean, (sum / 10) */
printf("The mean is %f", s / 10.0); /* should be 57.723 */
return 0;
}
|
C | #include<bits/stdc++.h>
using namespace std;
int main(){
cout << "400" << endl;
for(int i = 0;i<400;i++){
cout << i << " ";
}
cout << endl;
for(int i = 0;i<400;i++){
cout << i*i << " ";
}
cout << endl;
} |
C | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "item.h"
Item *NewItem(const char *path)
{
if(path == NULL)
return NULL;
Item *pitem = (Item *)malloc(sizeof(Item));
if(pitem == NULL)
{
printf("[-] NewItem Fail\n");
exit(0);
}
memset(pitem, 0, sizeof(Item));
size_t path_size = strlen(path);
pitem->path = (char *)malloc(path_size + 1);
strcpy(pitem->path, path);
if(GetItemStat(pitem) < 0)
{
FreeItem(pitem);
pitem = NULL;
}
return pitem;
}
inline int GetItemStat(Item *pitem)
{
return stat(pitem->path, &(pitem->item_stat));
}
inline void FreeItem(Item *pitem)
{
if(!pitem)
return;
free(pitem->path);
free(pitem);
}
inline int LaterThan(Item *pItem1, Item *pItem2)
{
return pItem1->item_stat.st_atime > pItem2->item_stat.st_atime;
}
|
C | #include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *prev;
int data;
struct node *next;
};
/*Declaring global variable start node*/
struct node *start = NULL;
/** \brief : This function creates a new double linked list as per the user's input
* for number of nodes.
* \param : integer numOfNodes
* \return : void
*/
void *createNodes(int numOFNode)
{
/*Declaring variables*/
int nodeData1 = 0;
/*Creating a node and allocating space*/
start = (struct node*) malloc(sizeof(struct node));
printf("\nEnter data for node 1: ");
scanf("%d",&nodeData1);
/*Checking if start node is allocated memory*/
if(start == NULL)
{
printf("\nNo memory allocated");
}
/*Logic to create 1st node. Both prev and next will be NULL in this case*/
start->next = NULL;
start->data = nodeData1;
start->prev = NULL;
/*Creating another node which will be used to crete n number of nodes*/
struct node *insertNode = NULL;
struct node *temp = start;
/*Logic to create nodes as per user's input and makinig them doubly linked list*/
for(int i = 2; i<=numOFNode; i++)
{
int nodeData = 0;
/*Allocating memory to node*/
insertNode = (struct node*) malloc(sizeof(struct node));
printf("\nEnter data for node %d: ",i);
scanf("%d",&nodeData);
/*Logic to link the node with the previous node and make it double linked list.
Pointing next of node to NULL and prev to previous node*/
insertNode->data = nodeData;
insertNode->next = NULL;
insertNode->prev = temp;
/*Linking the previous node to new node inserted*/
temp->next = insertNode;
/*Moving to the next node*/
temp = temp->next;
}
}
/** \brief : This function is used to display the final linked list.
* \param : start node
* \return : void
*/
void displayList(struct node *head)
{
/*Logic to iterate over the list and print data*/
printf("\nFinal List: ");
while(head != NULL)
{
printf("\nData: %d",head->data);
/*Condition to check the previous data as it is double link list*/
if(head->prev == NULL)
{
printf(" Prev: %d",0);
}
else
{
printf(" Prev: %d",head->prev->data);
}
head = head->next;
}
}
/** \brief : This function deletes a node from the beginning of the list.
* \param : structure
* \return : void
*
*/
void deleteAtBeginning(struct node *head)
{
/*Declare a node and allocate memory*/
struct node *deleteTemp = NULL;
deleteTemp = (struct node*) malloc(sizeof(struct node));
/*Logic to delete node at beginning of list by allocating next of the node into a
temporary node and then making next of the node as NULL. Lastly assign temporary node
as start or head node.*/
deleteTemp = head->next;
head->next = NULL;
start = deleteTemp;
}
/** \brief : This function deletes a node at the end of the list.
* \param : structure node
* \return : void
*/
void deleteAtEnd(struct node *head)
{
/*Logic to find the end of the list*/
while(head->next != NULL)
{
head = head->next;
}
/*Logic to delete last node by making next and previous node to NULL*/
head->prev->next = NULL;
head->prev = NULL;
}
/** \brief : This function deletes nodes between the list.
* \param : structure node
* \return : void
*/
void deleteBetweenNode(struct node *head)
{
/*Ask user to enter which node to be deleted*/
printf("\nEnter node number to be deleted: ");
int deleteNodeNum = 0;
scanf("%d",&deleteNodeNum);
int deleteCount = 1;
/*Logic to check the node to be deleted*/
while(head != NULL)
{
if(deleteNodeNum == deleteCount)
{
break;
}
deleteCount++;
head = head->next;
}
/*Logic to delete node in between the node by linking the previous node to
the node next to the head*/
head->prev->next = head->next;
head->next->prev = head->prev;
head->next = NULL;
head->prev = NULL;
}
/** \brief : This function reverses a list.
* \param : struct node
* \return : void
*/
void reverseDoubleLinkList(struct node *head)
{
/*Logic to reach the end of the linked list*/
while(head->next != NULL)
{
head = head->next;
}
/*Logic to print the list in reverse order*/
printf("\nReverse list: ");
while(head != NULL)
{
printf("%d ",head->data);
head = head->prev;
}
}
int main()
{
/*Executing all the functions*/
int numOfNodes = 0;
printf("Number of nodes to create: ");
scanf("%d",&numOfNodes);
createNodes(numOfNodes);
displayList(start);
printf("\nAfter deleting 1st node: ");
deleteAtBeginning(start);
displayList(start);
printf("\nDelete last node: ");
deleteAtEnd(start);
displayList(start);
deleteBetweenNode(start);
displayList(start);
reverseDoubleLinkList(start);
return 0;
}
|
C | //
// Header.h
// Stack
//
// Created by MacBook on 2018/9/25.
// Copyright © 2018 MacBook. All rights reserved.
//
//
// SeqStack.hpp
// blabla
//
// Created by MacBook on 2018/9/24.
// Copyright © 2018年 MacBook. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define initSize 100
#define increment 20
typedef char SElemType;
typedef int AElemType;
typedef struct{
SElemType *elem;
AElemType *number;
int maxSize,top;
}SeqStack;
void initStack(SeqStack& S){ //初始化
S.elem=(SElemType*)malloc(initSize*sizeof(SElemType));
S.maxSize=initSize; S.top=-1;
}
bool stackEmpty(SeqStack& S){ //判断栈空
return S.top==-1;
}
bool stackFull(SeqStack& S){ //判断栈满
return S.top==S.maxSize-1;
}
void overFlow(SeqStack& S){ //栈满处理
int newSize=S.maxSize+increment;
SElemType *newS=(SElemType *)malloc(newSize*sizeof(SElemType));
for(int i=0;i<S.top;i++)
newS[i]=S.elem[i];
free(S.elem);
S.elem=newS;
S.maxSize=newSize;
}
void Push(SeqStack& S,SElemType x){ //若栈不满,则新元素进栈
if(stackFull(S))overFlow(S);
S.top++;
S.elem[S.top]=x;
}
bool Pop(SeqStack &S,SElemType &x)
{
if(stackEmpty(S))return false;
x=S.elem[S.top];S.top--;
return true;
}
int isp(char op){
if(op=='+'||op=='-') return 3;
else if(op=='#') return 0;
else if(op=='(') return 1;
else if(op=='*'||op=='/') return 5;
else if(op==')') return 6;
else return 0;
}
int icp(char op){
if(op=='+'||op=='-') return 2;
else if(op=='#') return 0;
else if(op=='(') return 6;
else if(op=='*'||op=='/') return 4;
else if(op==')') return 1;
else return 0;
}
char DoOperator(char op,char right,char left){ //从操作数栈OPND中取两个操作数,根据操作符op形成运算指令并计算
char result;
right=right-'0';
left=left-'0';
switch(op){
case'+':result=left+right;break;
case'-':result=left-right;break;
case'*':result=left*right;break;
case'/':result=left/right;break;
}
return result;
}
bool getTop(SeqStack &S,SElemType &x)
{
if(stackEmpty(S))return false;
x=S.elem[S.top];
return true;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main() {
int i = 0xefffffff;
printf("%d\n", i);
char *b = (char *)&i;
printf("%d, %d\n", *b == 0x34, *(b + 1) == 0x12);
}
|
C | #include <conio.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main ()
{
srand(time(0));
double v[1000], num, menor, maior;
int i;
do{
printf("Digite o numero desejado, entre 1 e 1000.");
scanf ("%lf", &num);
}while (num<1||num>1000);
for (i=0; i<num; i++)
{
v[i] = rand()%10;
}
menor = v[0];
maior = v[0];
for (i=0; i<num; i++)
{
if(v[i]<menor)
menor = v[i];
if(v[i]>maior)
maior = v[i];
}
printf("O maior numero eh %.2lf e o menor %.2lf.\n", maior, menor);
getch ();
return 0;
}
|
C | /**
* Forking a process a thrice
* Result: 8 times "Hello" would be printed
* Explanation: @TODO
*/
#include <unistd.h>
#include <string.h>
int main()
{
fork();
fork();
fork();
char str[] = "Hello\n";
write(0, str, strlen(str));
return 0;
} |
C | #define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
int NumbOfBit(int i);
int main(int argc, char* argv[])
{
assert(NumbOfBit(256) == 1);
assert(NumbOfBit(-1) == 32);
assert(NumbOfBit(254) == 7);
assert(NumbOfBit(1) == 1);
assert(NumbOfBit(255) == 8);
assert(NumbOfBit(-255) == 25);
assert(NumbOfBit(10) == 2);
assert(NumbOfBit(-5) == 31);
assert(NumbOfBit(0) == 0);
return 0;
}
int NumbOfBit(int number)
{
int c = 0;
for (int i = 0; i < sizeof(int) * 8; i++, number >>= 1) {
number & 1 == 1 ? c++ : 1;
}
__asm { mov eax, c}
}
|
C | /* ESP32 Pointer exploit Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#define TAG "test"
#define MAX_SSID_LEN 20
#define MAX_PASSWORD_LEN 30
struct command
{
unsigned int resp_offset;
unsigned int pin_len;
char buf[0];
};
int copy_pin(struct command *dest, struct command *src)
{
char *d;
int i;
char *pin;
if (!dest || !src) {
ESP_LOGE(TAG, "dest or src is NULL\n");
return ESP_FAIL;
}
pin = malloc(src->pin_len);
if (pin == NULL) {
ESP_LOGE(TAG, "malloc failed");
return ESP_FAIL;
}
memcpy(pin, src->buf, src->pin_len);
for (i = 0; i < src->pin_len; i++) {
if (pin[i] == '\0') {
ESP_LOGE(TAG, "PIN is wrong");
return ESP_FAIL;
}
}
d = dest->buf + src->resp_offset;
memcpy(d,pin,src->pin_len);
free(pin);
return ESP_OK;
}
int parse_data(char *data, int len)
{
char buf[100]={0};
if (!data) {
ESP_LOGE(TAG, "data is NULL\n");
return ESP_FAIL;
}
if (len > sizeof(buf)) {
ESP_LOGE(TAG, "len > sizeof(buf) = %d > %d", len, sizeof(buf));
return ESP_FAIL;
}
return copy_pin((struct command *)buf,(struct command *)data);
}
void _print_error(void)
{
ESP_LOGE(TAG, "SHALL NOT BE HERE %s:%d", __FUNCTION__, __LINE__);
return;
}
void exploit_main(void)
{
//Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
int buf[3];
buf[0] = -0x50; //pin_start
buf[1] = 4; //pin_len
buf[2] = (int)_print_error+3;
ESP_LOGI(TAG, "final string: %s string end", (char*)buf);
(void) parse_data((char *)buf,sizeof(buf));
ESP_LOGE(TAG, "%s:%d", __FUNCTION__, __LINE__);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <unistd.h> //usleep
#include <signal.h>
#include <pthread.h>
#define checkError(ret) do{if(-1==ret){printf("[%d]err:%s\n", __LINE__, strerror(errno));exit(1);}}while(0)
static void *SendMsgThread(void *arg);
int iSocketFd = 0;
int main(int argc, char const *argv[])
{
printf("this is a tcp client demo\n");
signal(SIGPIPE, SIG_IGN);//ingnore signal interference
iSocketFd = socket(AF_INET, SOCK_STREAM, 0);
checkError(iSocketFd);
int re = 1;
checkError(setsockopt(iSocketFd, SOL_SOCKET, SO_REUSEADDR, &re, sizeof(re)));
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); /*receive any address*/
//server_addr.sin_addr.s_addr = inet_addr("10.128.118.43");
server_addr.sin_port = htons(7878);
while(1){
printf("conncet to server...\n");
if(-1 != connect(iSocketFd, (struct sockaddr *)&server_addr, sizeof(server_addr))){
break;
}
sleep(1);
}
pthread_t send_thread;
if (pthread_create(&send_thread, NULL, SendMsgThread, NULL))
{
printf("err:%s\n", strerror(errno));
return -1;
}
const char *aSend = "012345678987654321001234567898765432100123456789876543210\n";
while(1)
{
checkError(send(iSocketFd, aSend, strlen(aSend), 0));
sleep(0);
}
return 0;
}
static void *SendMsgThread(void *arg)
{
printf("SendMsgThread\n");
char *sendstr = "012345678987654321001234567898765432100123456789876543210\n";
while(1){
checkError(send(iSocketFd, sendstr, strlen(sendstr), 0));
sleep(0);
}
pthread_exit(0);
} |
C | int main(void) {
int x = 1;
/* if 语句前 */
if (x > 0) {
/* 为正时的处理 */
x = 1;
} else if (x < 0) {
/* 为负时的处理 */
x = -1;
} else {
/* 为零时的处理 */
x = 0;
}
/* if 语句后 */
x *= 2;
return x;
}
|
C | #include "ftsh.h"
#include "exp_arith.h"
int init_toks_clean(t_tok *d, t_tok **c)
{
int k;
k = 0;
if (!(*c = (t_tok*)malloc(sizeof(t_tok) * (get_tok_len(d) + 1))))
clean_exit(1, MALLOC_ERR);
while (k <= get_tok_len(d))
{
(*c)[k].token = 0;
(*c)[k].value = 0;
(*c)[k].varid = -2;
(*c)[k].varname = NULL;
(*c)[k].beg = 0;
(*c)[k].end = 0;
k++;
}
return (0);
}
void c_iter(t_tok *d, t_tok **c, int *i, int *k)
{
if (*k != 0)
{
if (d[*i].token == tk_varmin)
(*c)[*k - 1].end = -1;
if (d[*i].token == tk_varplus)
(*c)[*k - 1].end = 1;
}
if (d[*i].token == tk_plusvar)
(*c)[*k].beg = 1;
if (d[*i].token == tk_minvar)
(*c)[*k].beg = -1;
}
int check_put_oper(int prev, t_tok *dirty, int i)
{
if (prev == 'n' || (check_next_tok(dirty, i) != tk_nb
&& check_next_tok(dirty, i) != tk_plusvar
&& check_next_tok(dirty, i) != tk_minvar))
return (1);
return (0);
}
void invert_value(int *i)
{
if (*i == -1)
*i = 1;
else
*i = -1;
}
void insert_clean_token(t_tok *d, t_tok **c, t_integ *v)
{
(*c)[v->k++].token = d[v->i].token;
v->prev = d[v->i].token;
}
|
C | /*
============================================================================
Name : FileOperater.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
r 打开 只读文件,该文件必须存在。
r+ 打开可读写的文件,该文件必须存在。
w 打开 只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。
a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。
上述的形态字符串都可以再加一个b字符,如rb、w+b或ab+等组合,加入b 字符用来告诉函数库打开的文件为二进制文件,而非纯文字文件。
============================================================================
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "wave.h"
extern const uint32_t DWWAV_RIFF;
extern const uint32_t DWWAV_WAVE;
extern const uint32_t DWWAV_FMT;
extern const uint32_t DWWAV_DATA;
//注意属性中的比特率是176kbps,而1CH中为22050Byte/s,换算一下就会发现22050*8/1024并不等于176,而是等于172,这里我想可能是通信中的1K并不等于1024而是等于1000的原因(通信原理书中好像有),如果按22050*8/1000这样算,就正好等于176了。其实比特率也可以这样算,总字节除以时长得到每秒字节率,再乘以8除以1000就得到比特率了,即(1325000/60)*8/1000=176kbps。
typedef struct {
// RIFF_HEADER
//uint8_t chRIFF[4]; //00H 4byte 52 49 46 46 RIFF,资源交换文件标志。
uint32_t chriff;
uint32_t wavlen;//04H 4byte 从下一个地址开始到文件尾的总字节数。高位字节在后面,这里就是001437ECH,换成十进制是1325036byte,算上这之前的8byte就正好1325044byte了。
//uint8_t chWAV[4]; //08H 4byte 57 41 56 45 WAVE,代表wav文件格式。
uint32_t chwav;
//uint8_t chFMT[4]; //0CH 4byte 66 6D 74 20 FMT ,波形格式标志
uint32_t chfmt;
uint32_t PcmSize;//10H 4byte 00000010H,16PCM,这个对应定义中的PCMWAVEFORMAT部分的大小,可以看到后面的这个段内容正好是16个字节。当为16时,最后是没有附加信息的,当为数字18时,最后多了两个字节的附加信息
// PCMWAVEFORMAT
//formart;
uint16_t FormatTag; //14H 2byte 为1时表示线性PCM编码,大于1时表示有压缩的编码。这里是0001H。
//CHnum;
uint16_t Channels; //16H 2byte 1为单声道,2为双声道,这里是0001H。
//SampleRate;
uint32_t SamplesPerSec; //18H 4byte 采样频率,这里是00002B11H,也就是11025Hz。
//speed; 比特率=AvgBytesPerSec*8/1000
uint32_t AvgBytesPerSec;//1CH 4byte 每秒所需字节数 | =采样频率SamplesPerSec*音频通道数Channels*每次采样得到的样本位数BitsPerSample/8,00005622H,也就是22050Byte/s=11025*1*16/2。
//ajust;
uint16_t BlockAlign;//20H 2byte 每个采样需要字节数 | 数据块块对齐单位=通道数*每次采样得到的样本位数/8,0002H,也就是2=1*16/8。
//SampleBits;
uint16_t BitsPerSample; //22H 2byte 每个采样位数BitsPerSample,0010H即16,一个量化样本占2byte。
//uint8_t chDATA[4]; //24H 4byte data,一个标志而已。
uint32_t chdata;
uint32_t DATAlen;//28H 4byte Wav文件实际音频数据所占的大小,这里是001437C8H即1325000,再加上2CH就正好是1325044,整个文件的大小。
} WAV_head_t;
typedef union {
WAV_head_t wavhead;
uint8_t wavbuf[0x2C];
} WAVE_info_u;
WAV_head_t wav1;
uint8_t CHanalnum;
uint8_t Bitnum;
uint8_t DACdone;
WAVE_info_u wavinfo;
uint8_t Check_Ifo(uint8_t* pbuf1, uint8_t* pbuf2) {
uint8_t i;
for (i = 0; i < 4; i++)
if (pbuf1[i] != pbuf2[i])
return 1;
return 0;
}
uint8_t WAV_Init(uint8_t* pbuf) //初始化并显示文件信息 注: 仅适用于没有fact区的wav文件
{
int i;
uint8_t *pbuf0 = pbuf;
//取得WAV文件头
for (i = 0; i < 0x2C; i++)
wavinfo.wavbuf[i] = *(pbuf0++);
if (wavinfo.wavhead.chriff != DWWAV_RIFF) {
printf("RIFF标志错误\n");
// return 1; //RIFF标志错误
}
//wav1.wavlen = Get_num(pbuf + 4, 4); //文件长度,数据偏移4byte
if (wavinfo.wavhead.chwav != DWWAV_WAVE) {
printf("WAVE标志错误\n");
// return 2; //WAVE标志错误
}
if (wavinfo.wavhead.chfmt != DWWAV_FMT) {
printf("FMT标志错误\n");
// return 3; //fmt标志错误
}
if (wavinfo.wavhead.chdata != DWWAV_DATA) {
printf("data标志错误\n");
// return 4; //data标志错误
}
printf("offset:0x%x %d\n",
wavinfo.wavhead.wavlen - wavinfo.wavhead.DATAlen + 8,
wavinfo.wavhead.wavlen - wavinfo.wavhead.DATAlen + 8);
printf("filesize: %d\n", wavinfo.wavhead.wavlen + 8);
printf("wavlen: %d\n", wavinfo.wavhead.wavlen);
printf("DATAlen: %d\n", wavinfo.wavhead.DATAlen);
printf("声道Channels: %d\n", wavinfo.wavhead.Channels);
printf("采样字节数 BlockAlign: %d\n", wavinfo.wavhead.BlockAlign);
printf("采样位数BitsPerSample: %d\n", wavinfo.wavhead.BitsPerSample);
printf("采样频率SamplesPerSec: %d\n", wavinfo.wavhead.SamplesPerSec);
printf("比特率AvgBytesPerSec: %dkps\n",
wavinfo.wavhead.AvgBytesPerSec * 8 / 1000);
return 0;
}
int main0(void) {
// puts("!!!Hello World!!!"); // prints !!!Hello World!!!
FILE *fp2;
int c;
fp2 = fopen("a.txt", "r");
while ((c = fgetc(stdin)) != EOF)
printf("0X%x\n", c);
fclose(fp2);
return EXIT_SUCCESS;
}
#define BETWEEN(VAL, vmin, vmax) ((VAL) >= (vmin) && (VAL) <= (vmax))
#define ISHEXCHAR(VAL) (BETWEEN(VAL, '0', '9') || BETWEEN(VAL, 'A', 'F') || BETWEEN(VAL, 'a', 'f'))
char BYTE2HEX(uint8_t int_val)
{
if (BETWEEN(int_val, 0, 9))
{
return int_val + 0x30;
}
if (BETWEEN(int_val, 0xA, 0xF))
{
return (int_val - 0xA) + 'A';
}
return '0';
}
int main(int argc, char **argv) {
FILE *fpi;
FILE *fpo;
char *str2=argv[2];
char * strn = "\n";
uint8_t buffer[1];
uint8_t str[6];
uint8_t len =1;
uint8_t nam[100];
int i;
printf("parament num: %d\n", argc);
if (argc == 2) {
wav_open(argv[1]);
} else if(argc == 3){
wav_open(argv[1]);
fpi =fopen(argv[1], "rb+");
if (NULL == fpi)
return 0;
printf("%s\n", argv[2]);
fpo =fopen(argv[2], "ab+");
if (NULL == fpo)
return 0;
for(i=0;*str2;i++){
if(*str2++ == '.'){
break;
}
printf("%d", i);
}
printf("write: %d\n", len);
str[0]='0';
str[1]='x';
str[4]=',';
str[5]=' ';
//写入头
fwrite ("#include \"stdint.h\"\n", 1, 20, fpo);
fwrite ("const uint8_t WAV_", 1, 18, fpo);
fwrite (argv[2], 1, i, fpo);
fwrite ("[]={\n", 1, 5, fpo);
i=1;
while(fread(buffer, 1, 1, fpi)){
str[2] = BYTE2HEX((uint8_t)((buffer[0]>>4)&0x0F));
str[3] = BYTE2HEX((uint8_t)((buffer[0])&0x0F));
fwrite (str, 1, 6, fpo);
if(!(i++%16)){
fwrite ("\n", 1, 1, fpo);
}
}
fwrite ("\n};", 1, 2, fpo);
}else {
wav_open("D:\\Program Files\\BaiduYunGuanjia\\sounds\\5.wav");
}
}
int main1() {
int i;
unsigned char s[1024] = { 0 };
FILE *fp = NULL;
printf("open 000.wav");
if (NULL
== (fp = fopen("D:\\Program Files\\BaiduYunGuanjia\\sounds\\1.wav",
"rb+")))
// if (NULL == (fp = fopen("D:\\work\\PARKING\\yyzdbssc\\notify.wav", "rb+")))
// if (NULL == (fp = fopen("D:\\work\\PARKING\\yyzdbssc\\notify.wav", "rb+")))
// if (NULL == (fp = fopen("D:\\work\\PARKING\\yyzdbssc\\001.wav", "rb+")))
return 0;
// 参数:第一个参数为接收数据的指针(buff),也即数据存储的地址
// 第二个参数为单个元素的大小,即由指针写入地址的数据大小,注意单位是字节
// 第三个参数为元素个数,即要读取的数据大小为size的元素个素
// 第四个参数为提供数据的文件指针,该指针指向文件内部数据
// 返回值:读取的总数据元素个数
printf("opened 000.wav\n");
fread(s, 256, 1, fp);
WAV_Init(s);
for (i = 0; i < 0x2C; i++) {
if (!(i % 16)) {
printf("\n");
}
printf("%02x ", s[i]);
}
}
/* void main2()
{
FILE *fp = NULL;
short i,j; //勿定义为BYTE, 否则无限循环.
if(NULL == (fp = fopen("a.bin","ab+")))
return;
// for(i=0;i<=0xFF;++i)
for(j=0;j<=0xFF;++j)
{
// fputc(0x20,fp);
// fputc(0x20,fp);
fputc(j,fp);
}
fclose(fp);
if(NULL == (fp = fopen("*.txt","ab+")))
puts("!!!Hello World!!!");
}
int FileWrite(char* s,FILE *fp){
if(NULL == (fp = fopen("a.txt","w+b")))
return;
printf("%d\n", fwrite(s,sizeof(s),10,fp));
//s 待写入数据的指针
//sizeof(s) 每次写入数据的大小
//10 写入数据的总大小 10*sizeof(s)
//要写入文件的指针
fclose(fp);
}*/
int main2() {
FILE *fp = NULL;
// char s11[1024]={0x31,32,33,34,35,36,37,38,39};
unsigned char s[1024] = { 0 };
// short i,j; //勿定义为BYTE, 否则无限循环.
unsigned int i, j, compare;
unsigned int total, adds, min;
puts("操作说明\n\n");
puts("1.把通话记录中需要统计的内容导出!\n");
puts("2.每条记录时间用空格或换行隔开!\n");
puts("3.注意最后一条记录后面一定要加空格或回车哦!");
puts("\nPress Enter To GO!");
while (!fgetc(stdin))
;
if (NULL == (fp = fopen("recoder.txt", "a+")))
return 0;
/* // for(i=0;i<=0xFF;++i)
for(j=0;j<=0xFF;++j)
{
// fputc(0x20,fp);
// fputc(0x20,fp);
fputc(j,fp);
fputc(0x0a,fp);
//printf("%d\n",ftell(fp));
}
// fread();
fclose(fp);
if(NULL == (fp = fopen("a.txt","ab+")))
return;
// printf("%d\n",s[2]);
fclose(fp);
*/
//fputs(fgets(s,80,stdin),stdout);
fread(s, 256, 1, fp);
//fgets(s,100,fp);
fclose(fp);
/*i=0;
while(s[i]){
printf("%x\n",s[i]);
i++;
}*/
i = 0;
j = 0;
compare = 0;
adds = 0;
min = 0;
total = 0;
//printf("adds=%d\n",adds);
while (s[i]) {
if ((s[i] > 0x29) && (s[i] < 0x40)) {
adds *= 10;
adds += s[i] - 0x30;
// printf("s[%d]=%x\n",i,s[i]);
}
i++;
// printf("adds=%d\n",adds);
if ((s[i] == 0x0a) || (s[i] == 0x0d) || (s[i] == 0x20)) {
// printf("adds2=%d\n", adds);
if (adds) {
if (adds % 60)
min = adds / 60 + 1;
else
min = adds / 60;
// printf("min=%d\n", min);
total += min;
if (!(total == compare)) {
j++;
compare = total;
printf("\n第%d条通话记录%d分钟\n", j, min);
}
// printf("total=%d\n", total);
}
adds = 0;
i++;
}
// printf("0x%x\n",s[i]);
// printf("%d\n",total);
}
printf("\n共%d条通话记录\n\n", j);
printf("\n您的通话时间为%d分钟\n\n", total);
// if(NULL == (fp = fopen("b.txt","w+")))return;
// fputs(s1,fp);
// fclose(fp);
puts("\nPress Twice Time Enter To Exit!");
while (!fgetc(stdin))
;
while (!fgetc(stdin))
;
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
void crearmatriz (int a[11][11], int ren, int col);
// int filas = (sizeof(edades)/sizeof(edades[0]));
// int columnas = (sizeof(edades[0])/sizeof(edades[0][0]));
void imprime (int a[11][11],int ren, int col);
void transpuesta (int a[11][11], int b[11][11], int ren, int col);
main(){
srand (time(NULL));
int i,j,tam,Tamanofilas,Tamanocolumnas,ren,col;
ren=rand()%10+1;
col=rand()%10+1;
int a[11][11],b[11][11];
crearmatriz(a,ren,col);
imprime(a,ren,col);
printf("\n");
transpuesta(a,b,ren,col);
imprime(b,col,ren);
MayorMenor(a,ren,col);
return 0;
}
void transpuesta (int a[11][11], int b[11][11], int ren, int col) {
int i,j;
for (i=0;i<ren;i++) {
for (j=0;j<col;j++) {
b[j][i]=a[i][j];
}
}
}
void imprime (int n[11][11],int ren, int col){
int i,j;
for (i=0;i<ren;i++) {
for (j=0;j<col;j++) {
printf("%d ",n[i][j]);
}
printf("\n");
}
}
void MayorMenor (int n[11][11],int ren, int col){
int i,j,MA=0,me=50;
for (i=0;i<ren;i++) {
for (j=0;j<col;j++) {
if(MA<n[i][j])
MA=n[i][j];
if(me>n[i][j])
me=n[i][j];
}
}
printf("\nMayor:%d\n",MA);
printf("Menor:%d",me);
}
void crearmatriz (int a[11][11],int ren, int col) {
int i, j;
for (i=0;i<ren;i++) {
for (j=0;j<col;j++) {
a[i][j]=rand()%10;
}
}
}
|
C | /******************************************************************************
* File:
* display.c
*
* Description:
* The library is responsible for displaying objects on LCD.
*
*****************************************************************************/
/************/
/* Includes */
/************/
#include "pre_emptive_os/api/osapi.h"
#include "pre_emptive_os/api/general.h"
#include "display.h"
#include "lcd.h"
/***********/
/* Defines */
/***********/
// colors for menu and messages
#define COLOR_GLOBAL_BACKGROUND 0x00
#define COLOR_MENU_BACKGROUND 0x00
#define COLOR_MESSAGE_BACKGROUND 0x00
#define COLOR_TEXT 0xff
/*************/
/* Functions */
/*************/
/*****************************************************************************
*
* Description:
* Displays game menu.
*
****************************************************************************/
void displayMenu(void) {
// sets background and text color
lcdColor(COLOR_GLOBAL_BACKGROUND, COLOR_TEXT);
// paints the screen with background color
lcdClrscr();
lcdRect(0, 20, 128, 88, COLOR_MENU_BACKGROUND);
lcdGotoxy(10, 54);
lcdPuts("Press joystick");
}
/*****************************************************************************
*
* Description:
* Displays text on the screen.
*
* Params:
* [in] text - text to be displayed
*
****************************************************************************/
void displayText(char *text) {
lcdRect(0, 60, 128, 30, COLOR_MESSAGE_BACKGROUND);
lcdGotoxy(10, 70);
lcdPuts(text);
}
/*****************************************************************************
*
* Description:
* The functions below display different types of game objects.
*
* Params:
* [in] x - x coordinate of the left side of object
* [in] y - y coordinate of the upper side of object
*
****************************************************************************/
void displayEmptyField(tU8 x, tU8 y) {
lcdRect(x, y, FIELD_SIZE, FIELD_SIZE, COLOR_BACKGROUND);
}
void displayWall(tU8 x, tU8 y) {
lcdRect(x, y, FIELD_SIZE, FIELD_SIZE, COLOR_WALL);
}
void displayPoint(tU8 x, tU8 y) {
displayEmptyField(x, y);
lcdRect(x + 2, y + 2, 2, 2, COLOR_POINT);
}
void displayBonus(tU8 x, tU8 y) {
displayEmptyField(x, y);
lcdRect(x + 1, y + 2, 4, 2, COLOR_BONUS);
lcdRect(x + 2, y + 1, 2, 4, COLOR_BONUS);
}
void displayDoors(tU8 x, tU8 y) {
lcdRect(x, y, FIELD_SIZE, FIELD_SIZE, COLOR_DOORS);
}
void displayGhost(tU8 x, tU8 y) {
lcdRect(x + 2, y, 2, 1, COLOR_GHOST);
lcdRect(x, y + 2, 1, 4, COLOR_GHOST);
lcdRect(x + 5, y + 2, 1, 4, COLOR_GHOST);
lcdRect(x + 1, y + 1, 4, 4, COLOR_GHOST);
lcdRect(x + 1, y + 2, 1, 1, COLOR_EYES);
lcdRect(x + 4, y + 2, 1, 1, COLOR_EYES);
}
void displayPacman(tU8 x, tU8 y) {
lcdRect(x, y + 2, 6, 2, COLOR_PACMAN);
lcdRect(x + 2, y, 2, 6, COLOR_PACMAN);
lcdRect(x + 1, y + 1, 4, 4, COLOR_PACMAN);
}
void displayEatableGhost(tU8 x, tU8 y) {
lcdRect(x + 2, y, 2, 1, COLOR_EATABLE_GHOST);
lcdRect(x, y + 2, 1, 4, COLOR_EATABLE_GHOST);
lcdRect(x + 5, y + 2, 1, 4, COLOR_EATABLE_GHOST);
lcdRect(x + 1, y + 1, 4, 4, COLOR_EATABLE_GHOST);
lcdRect(x + 1, y + 3, 1, 1, COLOR_EYES);
lcdRect(x + 4, y + 3, 1, 1, COLOR_EYES);
}
void displayEyes(tU8 x, tU8 y) {
lcdRect(x, y + 1, 4, 4, COLOR_EYES_BORDER);
lcdRect(x + 3, y + 2, 4, 4, COLOR_EYES_BORDER);
lcdRect(x + 1, y + 2, 1, 1, COLOR_EYES);
lcdRect(x + 4, y + 3, 1, 1, COLOR_EYES);
}
|
C | /*
* Author: Alina Bogdanova BS18-04
* Date: 25.09.19
* Description: a program that forks a child
* process, waits for 10 seconds and then
* sends a SIGTERM signal to the child
* Child process runs an infinite loop
* and print “I’m alive” every second
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#define BUFF_SIZE 100
int main(){
int pid;
if(pid=fork()){
// child
while(1){
printf("I'm available\n");
sleep(1);
}
}else{
// parent
sleep(10);
kill(pid, SIGTERM);
}
return 0;
}
/*
OUTPUT:
I'm available
I'm available
I'm available
I'm available
I'm available
I'm available
I'm available
I'm available
I'm available
I'm available
fish: “./ex5” terminated by signal SIGTERM (Polite quit request)
*/ |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wait.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
enum errors {
OK,
ERR_INCORRECT_ARGS,
ERR_SOCKET,
ERR_CONNECT
};
int init_socket(const char *ip, int port) {
printf("Connecting...\n");
//open socket, result is socket descriptor
int server_socket = socket(PF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
perror("Fail: open socket");
_exit(ERR_SOCKET);
}
//prepare server address
struct hostent *host = gethostbyname(ip);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);
memcpy(&server_address.sin_addr, host -> h_addr_list[0], sizeof(server_address.sin_addr));
//connection
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
memcpy(&sin.sin_addr, host->h_addr_list[0], sizeof(sin.sin_addr));
if (connect(server_socket, (struct sockaddr*) &sin, (socklen_t) sizeof(sin)) < 0) {
perror("Fail: connect");
_exit(ERR_CONNECT);
}
printf("Connected\n");
return server_socket;
}
char *read_word() {
char *word = NULL;
char c;
int i = 1;
while(1) {
c = getchar();
if (c != '\n') {
word = realloc(word, sizeof(char) * (i + 1));
word[i - 1] = c;
i++;
} else {
break;
}
}
if (i > 1) {
word[i - 1] = 0;
}
return word;
}
int main(int argc, char **argv) {
if (argc != 3) {
puts("Incorrect args.");
puts("./telnet <ip> <port>");
puts("Example:");
puts("./telnet 127.0.0.1 80");
return ERR_INCORRECT_ARGS;
}
int port = atoi(argv[2]);
int server = init_socket(argv[1], port); // (ip, port)
char *input = NULL;
char *request = NULL;
char c;
int i = 0;
if (fork() == 0) {
while(1) {
if (read(server, &c, 1) <= 0) {
printf("Server is down\n");
exit(1);
}
putchar(c);
fflush(stdout);
}
}
while(1) {
input = read_word();
if (!input) {
printf("Error occured\n");
break;
}
// 23 is the constant length of other characters in the GET request
request = realloc(request, sizeof(char) * (23 + strlen(argv[1]) + strlen(input)));
strncpy(request, "GET ", 5);
strncat(request, input, strlen(input));
strncat(request, " HTTP/1.1\nHost: ", 17);
strncat(request, argv[1], strlen(argv[1]));
strncat(request, "\n\n", 3);
write(server, request, strlen(request));
free(input);
}
wait(NULL);
close(server);
return OK;
}
|
C | #include <parse.h>
json_t *parse_single_day(json_t *root) {
if (!json_is_object(root)) {
fprintf(stderr, "error: invalid root object\n");
json_decref(root);
exit(EXIT_FAILURE);
}
json_t *data = json_object_get(root, "data");
if (!json_is_array(data)) {
fprintf(stderr, "error: data is not an array\n");
json_decref(root);
json_decref(data);
exit(EXIT_FAILURE);
}
json_t *day = json_array_get(data, 0);
if (!json_is_object(day)) {
fprintf(stderr, "error: day is not an object\n");
json_decref(root);
json_decref(data);
json_decref(day);
exit(EXIT_FAILURE);
}
json_t *editors = json_object_get(day, "editors");
json_t *entities = json_object_get(day, "entities");
json_t *languages = json_object_get(day, "languages");
json_t *operating_systems = json_object_get(day, "operating_systems");
json_t *projects = json_object_get(day, "projects");
json_t *json_root = json_object();
json_object_set(json_root, "editors", extract_name_time(editors));
json_object_set(json_root, "entities", extract_name_time(entities));
json_object_set(json_root, "languages", extract_name_time(languages));
json_object_set(json_root, "operating_systems", extract_name_time(operating_systems));
json_object_set(json_root, "projects", extract_name_time(projects));
json_decref(root);
json_decref(data);
json_decref(day);
json_decref(editors);
json_decref(entities);
json_decref(languages);
json_decref(operating_systems);
json_decref(projects);
return json_root;
}
json_t *extract_name_time(json_t *arr) {
size_t index;
json_t *val;
json_t *n_arr = json_array();
json_array_foreach(arr, index, val) {
json_t *e = json_object();
json_object_set(e, "name", json_object_get(val, "name"));
json_object_set(e, "total_seconds", json_object_get(val, "total_seconds"));
json_array_append(n_arr, e);
}
return n_arr;
}
|
C | #include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define IN 0
#define OUT 1
#define LOW 0
#define HIGH 1
#define LED_PIN 110
#define BUF_MAX 4
#define DIRECTION_MAX 50
static int gpio_exprot(int pin)
{
char buffer[BUF_MAX];
int len;
int fd;
fd = open("/sys/class/gpio/export",O_WRONLY);
if (fd < 0)
{
fprintf(stderr,"Failed to open exprot for writing!\n");
return(-1);
}
len = snprintf(buffer,BUF_MAX,"%d",pin);
if(write(fd,buffer,len) < 0)
{
fprintf(stderr,"Fail to exprot gpio!\n");
return -1;
}
close(fd);
return 0;
}
static int gpio_unexprot(int pin)
{
char buffer[BUF_MAX];
int len;
int fd;
fd = open("/sys/class/gpio/unexport",O_WRONLY);
if (fd < 0)
{
fprintf(stderr,"Failed to open unexprot for writing!\n");
return(-1);
}
len = snprintf(buffer,BUF_MAX,"%d",pin);
if(write(fd,buffer,len) < 0)
{
fprintf(stderr,"Fail to unexprot gpio!\n");
return -1;
}
close(fd);
return 0;
}
static int gpio_direction(int pin,int dir)
{
static const char dir_str[] = "in\0out";
char path[DIRECTION_MAX];
int fd;
snprintf(path,DIRECTION_MAX,"/sys/class/gpio/gpio%d/direction",pin);
fd = open(path,O_WRONLY);
if(fd < 0 )
{
fprintf(stderr,"Failed to open gpio direction for writing!\n");
return -1;
}
if(write(fd,&dir_str[dir == IN?0:3],(dir == IN?2:3)) < 0)
{
fprintf(stderr,"Failed to set direction!\n");
return -1;
}
close(fd);
return 0;
}
static int gpio_read(int pin)
{
char value_str[3];
char path[DIRECTION_MAX];
int fd;
snprintf(path,DIRECTION_MAX,"/sys/class/gpio/gpio%d/value",pin);
fd = open(path,O_RDONLY);
if(fd < 0 )
{
fprintf(stderr,"Failed to open gpio value for reading!\n");
return -1;
}
if(read(fd,value_str,sizeof(value_str)) < 0)
{
fprintf(stderr,"Failed to read value!\n");
return -1;
}
close(fd);
return 0;
}
static int gpio_write(int pin,int value)
{
static const char value_str[] = "01";
char path[DIRECTION_MAX];
int fd;
snprintf(path,DIRECTION_MAX,"/sys/class/gpio/gpio%d/value",pin);
fd = open(path,O_WRONLY);
if(fd < 0 )
{
fprintf(stderr,"Failed to open gpio value for writing!\n");
return -1;
}
if(write(fd,&value_str[value == LOW?0:1],1) < 0)
{
fprintf(stderr,"Failed to write value!\n");
return -1;
}
close(fd);
return 0;
}
int main (int agrc,char *agrv[])
{
gpio_exprot(LED_PIN);
gpio_direction(LED_PIN,OUT);
printf("led err blink!\n");
for (int i = 0;i < 10;i++)
{
gpio_write(LED_PIN,HIGH);
sleep(1);
gpio_write(LED_PIN,LOW);
sleep(1);
}
gpio_write(LED_PIN,LOW);
gpio_unexprot(LED_PIN);
printf("led err blink finish!\n");
return 0;
}
|
C | // Skeleton for lab 2
//
// Task 1 writes periodically RGB-images to the shared memory
//
// No guarantees provided - if bugs are detected, report them in the Issue tracker of the github repository!
#include <stdio.h>
#include "altera_avalon_performance_counter.h"
#include "includes.h"
#include "altera_avalon_pio_regs.h"
#include "sys/alt_irq.h"
#include "sys/alt_alarm.h"
#include "system.h"
#include "io.h"
#include "images_alt.h"
#include <stdlib.h>
#include <alt_types.h>
#define DEBUG 0
#define HW_TIMER_PERIOD 100 /* 100ms */
/* Definition of Task Stacks */
#define TASK_STACKSIZE 2048
OS_STK task1_stk[TASK_STACKSIZE];
OS_STK StartTask_Stack[TASK_STACKSIZE];
/* Definition of Task Priorities */
#define STARTTASK_PRIO 1
#define TASK1_PRIORITY 10
/* Definition of Task Periods (ms) */
#define TASK1_PERIOD 10000
#define SECTION_1 1
/*
* Function to convert image to ASCII image and print on console
*/
void print_ascii(alt_u8* img)
{
alt_u16 i,j;
alt_u8 sizeX = *img++, sizeY = *img++;
alt_u8 sizeImg = sizeX * sizeY;
unsigned char imgOut[sizeImg+3];
unsigned char symbols[16] = {32, 46, 59, 42, 115, 116, 73, 40, 106, 117, 86, 119, 98, 82, 103, 64};
imgOut[0] = sizeX ;
imgOut[1] = sizeY ;
imgOut[2] = *img++ ;
printf("ascii start");
// Comment this for-loop for printing ASCII
for(i = 0; i < sizeImg; i++)
{
imgOut[i+3] = symbols[(int)((*img++)/16)];
}
printf("sizeY = %d \n",imgOut[0]);
// Uncomment this for-loop for printing ASCII
for(i = 0; i < sizeY; i++)
{
for(j=0; j< sizeX;j++)
{
printf("%c",imgOut[j+(i*sizeX)]);
}
printf("\n");
}
}
/*
* Function to peform sobel edge detection
*/
void sobelFilter( alt_u8* compact_img, alt_u32 width, alt_u32 height )
{
alt_u8 i=0;
alt_u8 j=0;
alt_u32 img_size = width*height;
alt_u8 sobel_img[img_size];
alt_32 g_x = 0;
alt_32 g_y = 0;
for(i=1;i< height-1;i++)
{
for(j=1; j<width-1;j++)
{
g_x = compact_img[((i-1)*width)+(j-1)] - compact_img[((i-1)*width)+(j+1)] + (compact_img[((i)*width)+(j-1)]<<1)-(compact_img[((i)*width)+(j+1)]<<1)+ (compact_img[((i+1)*width)+(j-1)] -
compact_img[((i+1)*width)+(j+1)]);
g_y = compact_img[((i-1)*width)+(j-1)]+ (compact_img[((i-1)*width)+(j)]<<1)+compact_img[((i-1)*width)+(j+1)]-(compact_img[((i+1)*width)+(j-1)]+ (compact_img[((i+1)*width)+(j)]<<1)+
compact_img[((i+1)*width)+(j+1)]);
if(g_x < 0) g_x = 0- g_x;
if(g_y < 0) g_y = 0- g_y;
sobel_img[(i*width)+j] = (g_x + g_y)>>3;
}
}
print_ascii( sobel_img);
printf("printAscii done\n");
}
/*
* Function to read RGB image from SRAM, convert to grayscale and compact grayscale image.
*/
void rgbToGray(unsigned char* base)
{
alt_u32 i;
alt_u8 size_x = *base++;
alt_u8 size_y = *base++;
alt_u8 sizeImg = size_x * size_y;
unsigned char grayscale_img[ size_x * size_y + 3 ];
alt_u32 index = 0;
alt_u32 m =0;
alt_u8 n=0;
alt_u8 compact_index = 0;
alt_u8 compact_img[size_x/2*size_y/2];
grayscale_img[0] = size_x;
grayscale_img[1] = size_y;
// incrementing pointer to omit max color
grayscale_img[2] = *base++;
for(i = 0; i < sizeImg; i++)
{
grayscale_img[i+3] = (*base++) * 0.3125
+ (*base++) * 0.5625
+ (*base++) * 0.125;
}
alt_u32 offset =0;
for(n = 0; n<size_y-1;n++)
{
for(m =0; m <size_x-1; m++)
{
compact_img[compact_index] = grayscale_img[m+offset] ;
compact_index++;
m++;
}
offset = offset+ (size_x<<1);
n++;
}
printf("grayscale done\n");
// sobelFilter(compact_img, size_x/2, size_y/2);
print_ascii(grayscale_img);
}
/*
* Global variables
*/
int delay; // Delay of HW-timer
/*
* ISR for HW Timer
*/
alt_u32 alarm_handler(void* context)
{
OSTmrSignal(); /* Signals a 'tick' to the SW timers */
return delay;
}
// Semaphores
OS_EVENT *Task1TmrSem;
// SW-Timer
OS_TMR *Task1Tmr;
/* Timer Callback Functions */
void Task1TmrCallback (void *ptmr, void *callback_arg){
OSSemPost(Task1TmrSem);
}
void task1(void* pdata)
{
INT8U err;
INT8U value=0;
char current_image=0;
/* Sequence of images for measuring performance */
char number_of_images=3;
unsigned char* img_array[3] = {img1_32_32, img2_32_32, img3_32_32};
// unsigned char* img_array[3] = {rectangle32x32, circle32x32, rectangle40x40};
PERF_RESET(PERFORMANCE_COUNTER_0_BASE);
PERF_START_MEASURING (PERFORMANCE_COUNTER_0_BASE);
PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE, SECTION_1);
while(count>0)
{
// Process image
rgbToGray(img_array[current_image]);
// printf("hello world");
/* Increment the image pointer */
current_image=(current_image+1) % number_of_images;
count--;
//OSSemPend(Task1TmrSem, 0, &err);
}
PERF_END(PERFORMANCE_COUNTER_0_BASE, SECTION_1);
/* Print report */
perf_print_formatted_report
(PERFORMANCE_COUNTER_0_BASE,
ALT_CPU_FREQ, // defined in "system.h"
1, // How many sections to print
"Section 1" // Display-name of section(s).
);
OSSemPend(Task1TmrSem, 0, &err);
}
void StartTask(void* pdata)
{
INT8U err;
void* context;
static alt_alarm alarm; /* Is needed for timer ISR function */
/* Base resolution for SW timer : HW_TIMER_PERIOD ms */
delay = alt_ticks_per_second() * HW_TIMER_PERIOD / 1000;
printf("delay in ticks %d\n", delay);
/*
* Create Hardware Timer with a period of 'delay'
*/
if (alt_alarm_start (&alarm,
delay,
alarm_handler,
context) < 0)
{
printf("No system clock available!n");
}
/*
* Create and start Software Timer
*/
//Create Task1 Timer
Task1Tmr = OSTmrCreate(0, //delay
TASK1_PERIOD/HW_TIMER_PERIOD, //period
OS_TMR_OPT_PERIODIC,
Task1TmrCallback, //OS_TMR_CALLBACK
(void *)0,
"Task1Tmr",
&err);
if (DEBUG) {
if (err == OS_ERR_NONE) { //if creation successful
printf("Task1Tmr created\n");
}
}
/*
* Start timers
*/
//start Task1 Timer
OSTmrStart(Task1Tmr, &err);
if (DEBUG) {
if (err == OS_ERR_NONE) { //if start successful
printf("Task1Tmr started\n");
}
}
/*
* Creation of Kernel Objects
*/
Task1TmrSem = OSSemCreate(0);
/*
* Create statistics task
*/
OSStatInit();
/*
* Creating Tasks in the system
*/
err=OSTaskCreateExt(task1,
NULL,
(void *)&task1_stk[TASK_STACKSIZE-1],
TASK1_PRIORITY,
TASK1_PRIORITY,
task1_stk,
TASK_STACKSIZE,
NULL,
0);
if (DEBUG) {
if (err == OS_ERR_NONE) { //if start successful
printf("Task1 created\n");
}
}
printf("All Tasks and Kernel Objects generated!\n");
/* Task deletes itself */
OSTaskDel(OS_PRIO_SELF);
}
int main(void) {
printf("MicroC/OS-II-Vesion: %1.2f\n", (double) OSVersion()/100.0);
OSTaskCreateExt(
StartTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
(void *)&StartTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
STARTTASK_PRIO,
STARTTASK_PRIO,
(void *)&StartTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);
OSStart();
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtol.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wzei <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/04 20:20:18 by wzei #+# #+# */
/* Updated: 2019/01/05 11:07:59 by wzei ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#ifndef ULONG_MAX
# define ULONG_MAX ((unsigned long)(~0L))
#endif
#ifndef LONG_MAX
# define LONG_MAX ((long)(ULONG_MAX >> 1))
#endif
#ifndef LONG_MIN
# define LONG_MIN ((long)(~LONG_MAX))
#endif
static size_t proc_base(const char *inp, int *bs)
{
const char *s;
s = inp;
if ((*bs == 0 || *bs == 16) && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
{
s += 2;
*bs = 16;
}
if (*bs == 0)
*bs = (s[0] == '0' ? 8 : 10);
return (s - inp);
}
static int chk_valid_char(int c)
{
if (ft_isdigit(c))
{
c -= '0';
return (c);
}
else if (ft_isalpha(c))
{
c -= (ft_isupper(c) ? 'A' - 10 : 'a' - 10);
return (c);
}
return (-1);
}
static void init_lim(unsigned long *o, int *l, int sgn, int base)
{
*o = ((sgn == -1) ? -(unsigned long)LONG_MIN : LONG_MAX);
*l = (int)(*o % (unsigned long)base);
*o /= (unsigned long)base;
return ;
}
static char *proc_digits(int sb, unsigned long *ac, int *an, const char *s)
{
unsigned long cutoff;
int cutlim;
int c;
int base;
base = ((sb < 0) ? -sb : sb);
init_lim(&cutoff, &cutlim, sb / base, base);
*ac = 0;
*an = 0;
while ((c = *s++))
{
if ((c = chk_valid_char(c)) == -1)
break ;
if (c >= base)
break ;
if (*an < 0 || *ac > cutoff || (*ac == cutoff && c > cutlim))
*an = -1;
else
{
*an = 1;
*ac = *ac * base + c;
}
}
return ((char *)s);
}
long ft_strtol(const char *nptr, char **endptr, int base)
{
const char *s;
unsigned long acc;
int sgn;
int any;
any = 0;
sgn = 0;
s = ft_strnotwhgt(nptr);
s = ft_strsgnstat(s, &sgn);
s += proc_base(s, &base);
base = ((sgn == 0) ? ((sgn + 1) * base) : (sgn * base));
s = proc_digits(base, &acc, &any, s);
if (any < 0)
{
acc = ((sgn == -1) ? LONG_MIN : LONG_MAX);
}
else if (sgn == -1)
acc = -(acc);
if (endptr != NULL)
*endptr = (char *)(any ? s - 1 : nptr);
return (acc);
}
|
C | /*
TITLE: Evaluation of Postfix Expression
NAME:Tauseef Mushtaque Ali Shaikh
CLASS: S.Y.[CO]
ROLLNO: 18CO63
SUBJECT: DS
DATE: 19/8/19
DISCRIPTION: In this Program a Postfix Expression is Evaluated and Result is Stored in a Stack.
*/
#include<stdio.h>
#include<stdlib.h>
#define max 50
struct stack
{
int data[max];
int top;
};
int empty(struct stack *s)
{
return (s->top==-1)?1:0;
}
void push(struct stack *s,int ele)
{
if (s->top < max-1)
s->data[++s->top]=ele;
else
printf("\nSTACK OVERFLOW");
}
int pop(struct stack *s)
{
if(!empty(s))
return s->data[s->top--];
else
return (int)-1;
}
int eval(char *expr)
{
char c;
int i,res,op2;
struct stack st;
st.top=-1;
for(i=0;expr[i]!='\0';i++)
{
c=expr[i];
switch(c)
{
case '+':
op2=pop(&st);
res=pop(&st)+op2;
push(&st,res);
break;
case '-':
op2=pop(&st);
res=pop(&st)-op2;
push(&st,res);
break;
case '*':
op2=pop(&st);
res=pop(&st)*op2;
push(&st,res);
break;
case '/':
op2=pop(&st);
res=pop(&st)/op2;
push(&st,res);
break;
case '%':
op2=pop(&st);
res=pop(&st)%op2;
push(&st,res);
break;
case '$':
op2=pop(&st);
res=pow(pop(&st),op2);
push(&st,res);
break;
case '0':
exit(0);
break;
default:
push(&st,c-'0');
}
}
return pop(&st);
}
int main()
{
while(1)
{
char *postfix;
int res;
postfix=(char*)malloc(1);
printf("\nEnter postfix Expression:");
scanf("%s",postfix);
res=eval(postfix);
printf("\n Evalution to Postfix Expression is : %d\n",res);
printf("\nEnter 0 to exit the program\n");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.