language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include "../common/global.h" #include "cpu.h" #ifdef ARCH_X86 #include "../x86/uarch.h" #include "../x86/apic.h" #elif ARCH_PPC #include "../ppc/uarch.h" #elif ARCH_ARM #include "../arm/uarch.h" #endif #define UNUSED(x) (void)(x) #define STRING_YES "Yes" #define STRING_NO "No" #define STRING_NONE "None" #define STRING_MEGAHERZ "MHz" #define STRING_GIGAHERZ "GHz" #define STRING_KILOBYTES "KB" #define STRING_MEGABYTES "MB" VENDOR get_cpu_vendor(struct cpuInfo* cpu) { return cpu->cpu_vendor; } int64_t get_freq(struct frequency* freq) { return freq->max; } #if defined(ARCH_X86) || defined(ARCH_PPC) char* get_str_cpu_name(struct cpuInfo* cpu, bool fcpuname) { #ifdef ARCH_X86 if(!fcpuname) { return get_str_cpu_name_abbreviated(cpu); } #elif ARCH_PPC UNUSED(fcpuname); #endif return cpu->cpu_name; } char* get_str_sockets(struct topology* topo) { char* string = emalloc(sizeof(char) * 2); int32_t sanity_ret = snprintf(string, 2, "%d", topo->sockets); if(sanity_ret < 0) { printBug("get_str_sockets: snprintf returned a negative value for input: '%d'", topo->sockets); return NULL; } return string; } uint32_t get_nsockets(struct topology* topo) { return topo->sockets; } #endif int32_t get_value_as_smallest_unit(char ** str, uint32_t value) { int32_t ret; int max_len = 10; // Max is 8 for digits, 2 for units *str = emalloc(sizeof(char)* (max_len + 1)); if(value/1024 >= 1024) ret = snprintf(*str, max_len, "%.4g"STRING_MEGABYTES, (double)value/(1<<20)); else ret = snprintf(*str, max_len, "%.4g"STRING_KILOBYTES, (double)value/(1<<10)); return ret; } // String functions char* get_str_cache_two(int32_t cache_size, uint32_t physical_cores) { char* tmp1; char* tmp2; int32_t tmp1_len = get_value_as_smallest_unit(&tmp1, cache_size); int32_t tmp2_len = get_value_as_smallest_unit(&tmp2, cache_size * physical_cores); // tmp1_len for first output, 2 for ' (', tmp2_len for second output and 7 for ' Total)' uint32_t size = tmp1_len + 2 + tmp2_len + 7 + 1; char* string = emalloc(sizeof(char) * size); if(tmp1_len < 0) { printBug("get_value_as_smallest_unit: snprintf failed for input: %d\n", cache_size); return NULL; } if(tmp2_len < 0) { printBug("get_value_as_smallest_unit: snprintf failed for input: %d\n", cache_size * physical_cores); return NULL; } if(snprintf(string, size, "%s (%s Total)", tmp1, tmp2) < 0) { printBug("get_str_cache_two: snprintf failed for input: '%s' and '%s'\n", tmp1, tmp2); return NULL; } free(tmp1); free(tmp2); return string; } char* get_str_cache_one(int32_t cache_size) { char* string; int32_t str_len = get_value_as_smallest_unit(&string, cache_size); if(str_len < 0) { printBug("get_value_as_smallest_unit: snprintf failed for input: %d", cache_size); return NULL; } return string; } char* get_str_cache(int32_t cache_size, int32_t num_caches) { if(num_caches > 1) return get_str_cache_two(cache_size, num_caches); else return get_str_cache_one(cache_size); } char* get_str_l1i(struct cache* cach) { return get_str_cache(cach->L1i->size, cach->L1i->num_caches); } char* get_str_l1d(struct cache* cach) { return get_str_cache(cach->L1d->size, cach->L1d->num_caches); } char* get_str_l2(struct cache* cach) { assert(cach->L2->exists); return get_str_cache(cach->L2->size, cach->L2->num_caches); } char* get_str_l3(struct cache* cach) { if(!cach->L3->exists) return NULL; return get_str_cache(cach->L3->size, cach->L3->num_caches); } char* get_str_freq(struct frequency* freq) { //Max 3 digits and 3 for '(M/G)Hz' plus 1 for '\0' uint32_t size = (5+1+3+1); assert(strlen(STRING_UNKNOWN)+1 <= size); char* string = emalloc(sizeof(char)*size); memset(string, 0, sizeof(char)*size); if(freq->max == UNKNOWN_DATA || freq->max < 0) snprintf(string,strlen(STRING_UNKNOWN)+1,STRING_UNKNOWN); else if(freq->max >= 1000) snprintf(string,size,"%.3f "STRING_GIGAHERZ,(float)(freq->max)/1000); else snprintf(string,size,"%d "STRING_MEGAHERZ,freq->max); return string; } char* get_str_peak_performance(int64_t flops) { char* str; if(flops == -1) { str = emalloc(sizeof(char) * (strlen(STRING_UNKNOWN) + 1)); strncpy(str, STRING_UNKNOWN, strlen(STRING_UNKNOWN) + 1); return str; } // 7 for digits (e.g, XXXX.XX), 7 for XFLOP/s double flopsd = (double) flops; uint32_t max_size = 7+1+7+1; str = ecalloc(max_size, sizeof(char)); if(flopsd >= (double)1000000000000.0) snprintf(str, max_size, "%.2f TFLOP/s", flopsd/1000000000000); else if(flopsd >= 1000000000.0) snprintf(str, max_size, "%.2f GFLOP/s", flopsd/1000000000); else snprintf(str, max_size, "%.2f MFLOP/s", flopsd/1000000); return str; } void init_topology_struct(struct topology* topo, struct cache* cach) { topo->total_cores = 0; topo->cach = cach; #if defined(ARCH_X86) || defined(ARCH_PPC) topo->physical_cores = 0; topo->logical_cores = 0; topo->smt_supported = 0; topo->sockets = 0; #ifdef ARCH_X86 topo->smt_available = 0; topo->apic = emalloc(sizeof(struct apic)); #endif #endif } void init_cache_struct(struct cache* cach) { cach->L1i = emalloc(sizeof(struct cach)); cach->L1d = emalloc(sizeof(struct cach)); cach->L2 = emalloc(sizeof(struct cach)); cach->L3 = emalloc(sizeof(struct cach)); cach->cach_arr = emalloc(sizeof(struct cach*) * 4); cach->cach_arr[0] = cach->L1i; cach->cach_arr[1] = cach->L1d; cach->cach_arr[2] = cach->L2; cach->cach_arr[3] = cach->L3; cach->max_cache_level = 0; cach->L1i->exists = false; cach->L1d->exists = false; cach->L2->exists = false; cach->L3->exists = false; } void free_cache_struct(struct cache* cach) { for(int i=0; i < 4; i++) free(cach->cach_arr[i]); free(cach->cach_arr); free(cach); } void free_freq_struct(struct frequency* freq) { free(freq); } void free_hv_struct(struct hypervisor* hv) { free(hv); } void free_cpuinfo_struct(struct cpuInfo* cpu) { free_uarch_struct(cpu->arch); free_hv_struct(cpu->hv); #ifdef ARCH_X86 free(cpu->cpu_name); #endif free(cpu); }
C
#include <stdio.h> int main(void) { int p[] = {[5]=6}; printf("ֽڳΪ"); printf("%lu\n",sizeof p); printf("ÿֽͳΪ"); printf("%lu\n",sizeof (int)); printf("Ϊ"); printf("%lu\n",sizeof (p) / sizeof (int)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_expand.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gboucett <gboucett@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/04 02:05:46 by gboucett #+# #+# */ /* Updated: 2021/01/08 17:35:03 by gboucett ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_expand.h" static void ft_expand_str(char **str) { t_list *expansion; char *tmp; expansion = NULL; ft_expand_env(&expansion, *str); ft_expand_backslashs(&expansion); ft_quote_removal(expansion); tmp = *str; *str = ft_expanded_str(expansion); free(tmp); ft_lstclear(&expansion, ft_free_expansion); } static void ft_expand_args(char **args) { while (*args) ft_expand_str(args++); } static void ft_expand_redirs(t_redirect **redirs) { if (!redirs) return ; while (*redirs) { ft_expand_str(&((*redirs)->filename)); redirs++; } } void ft_expand(t_command *command) { ft_expand_args(command->args); ft_expand_redirs(command->redirects); }
C
/* <Reference> Title : A High-speed Masking Method to protect ARIA against Side Channel Analysis Written By : HeeSeok Kim, Tae Hyun Kim, Jeong-Choon Ryoo, Dong-Guk Han, SeokHie Hong Graduate School of Information Management and Security, Korea University, Electronics and Telecommunications Research Institute */ /* <논문 관련 추가 정보> 논문에 나와있는 [그림 3], [그림 4]의 '중간 마스킹 값'은 해당 값으로 마스킹을 적용하는 것이 아니라 해당 마스킹이 적용된 입력값이 들어온다는 의미임. 즉, '추가 연산'에 해당하는 부분만 매 라운드에 추가해주면 됨. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "ARIA.h" u8 CK1[16] = { 0x51, 0x7c, 0xc1, 0xb7, 0x27, 0x22, 0x0a, 0x94, 0xfe, 0x13, 0xab, 0xe8, 0xfa, 0x9a, 0x6e, 0xe0 }; u8 CK2[16] = { 0x6d, 0xb1, 0x4a, 0xcc, 0x9e, 0x21, 0xc8, 0x20, 0xff, 0x28, 0xb1, 0xd5, 0xef, 0x5d, 0xe2, 0xb0 }; u8 CK3[16] = { 0xdb, 0x92, 0x37, 0x1d, 0x21, 0x26, 0xe9, 0x70, 0x03, 0x24, 0x97, 0x75, 0x04, 0xe8, 0xc9, 0x0e }; /* Masking S-box를 생성하고 담을 변수 */ u8 maskS1box[256] = { 0x00 }; u8 maskS2box[256] = { 0x00 }; u8 maskinvS1box[256] = { 0x00 }; u8 maskinvS2box[256] = { 0x00 }; /* 랜덤으로 생성된 마스킹 값을 담을 배열 m XOR m' = m'' */ u8 mask[3] = { 0x00 }; u32 u4byte_in(u8* x) { return (x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3]; } void u4byte_out(u8* x, u32 y) { x[0] = (y >> 24) & 0xff; x[1] = (y >> 16) & 0xff; x[2] = (y >> 8) & 0xff; x[3] = y & 0xff; } void Masking_AddRoundKey(u8 S[], u8 RK[]) { S[0] ^= RK[0]; S[1] ^= RK[1]; S[2] ^= RK[2]; S[3] ^= RK[3]; S[4] ^= RK[4]; S[5] ^= RK[5]; S[6] ^= RK[6]; S[7] ^= RK[7]; S[8] ^= RK[8]; S[9] ^= RK[9]; S[10] ^= RK[10]; S[11] ^= RK[11]; S[12] ^= RK[12]; S[13] ^= RK[13]; S[14] ^= RK[14]; S[15] ^= RK[15]; } /* 각 라운드에서 추가 연산에 해당하는 부분을 연산하기 위한 함수 (0000m''m''m''m'')2 형태로 XOR 연산이 추가됨. */ void Masking_AddRoundKey2(u8 S[]) { S[4] ^= mask[2]; S[5] ^= mask[2]; S[6] ^= mask[2]; S[7] ^= mask[2]; S[12] ^= mask[2]; S[13] ^= mask[2]; S[14] ^= mask[2]; S[15] ^= mask[2]; } void Masking_SubstLayer(u8 S[], int round) { if (round % 2) { S[0] = maskS1box[S[0]]; S[1] = maskS2box[S[1]]; S[2] = maskinvS1box[S[2]]; S[3] = maskinvS2box[S[3]]; S[4] = maskS1box[S[4]]; S[5] = maskS2box[S[5]]; S[6] = maskinvS1box[S[6]]; S[7] = maskinvS2box[S[7]]; S[8] = maskS1box[S[8]]; S[9] = maskS2box[S[9]]; S[10] = maskinvS1box[S[10]]; S[11] = maskinvS2box[S[11]]; S[12] = maskS1box[S[12]]; S[13] = maskS2box[S[13]]; S[14] = maskinvS1box[S[14]]; S[15] = maskinvS2box[S[15]]; } else { S[0] = maskinvS1box[S[0]]; S[1] = maskinvS2box[S[1]]; S[2] = maskS1box[S[2]]; S[3] = maskS2box[S[3]]; S[4] = maskinvS1box[S[4]]; S[5] = maskinvS2box[S[5]]; S[6] = maskS1box[S[6]]; S[7] = maskS2box[S[7]]; S[8] = maskinvS1box[S[8]]; S[9] = maskinvS2box[S[9]]; S[10] = maskS1box[S[10]]; S[11] = maskS2box[S[11]]; S[12] = maskinvS1box[S[12]]; S[13] = maskinvS2box[S[13]]; S[14] = maskS1box[S[14]]; S[15] = maskS2box[S[15]]; } } void DiffLayer(u8 S[]) { u8 temp[16]; int i; temp[0] = S[3] ^ S[4] ^ S[6] ^ S[8] ^ S[9] ^ S[13] ^ S[14]; temp[1] = S[2] ^ S[5] ^ S[7] ^ S[8] ^ S[9] ^ S[12] ^ S[15]; temp[2] = S[1] ^ S[4] ^ S[6] ^ S[10] ^ S[11] ^ S[12] ^ S[15]; temp[3] = S[0] ^ S[5] ^ S[7] ^ S[10] ^ S[11] ^ S[13] ^ S[14]; temp[4] = S[0] ^ S[2] ^ S[5] ^ S[8] ^ S[11] ^ S[14] ^ S[15]; temp[5] = S[1] ^ S[3] ^ S[4] ^ S[9] ^ S[10] ^ S[14] ^ S[15]; temp[6] = S[0] ^ S[2] ^ S[7] ^ S[9] ^ S[10] ^ S[12] ^ S[13]; temp[7] = S[1] ^ S[3] ^ S[6] ^ S[8] ^ S[11] ^ S[12] ^ S[13]; temp[8] = S[0] ^ S[1] ^ S[4] ^ S[7] ^ S[10] ^ S[13] ^ S[15]; temp[9] = S[0] ^ S[1] ^ S[5] ^ S[6] ^ S[11] ^ S[12] ^ S[14]; temp[10] = S[2] ^ S[3] ^ S[5] ^ S[6] ^ S[8] ^ S[13] ^ S[15]; temp[11] = S[2] ^ S[3] ^ S[4] ^ S[7] ^ S[9] ^ S[12] ^ S[14]; temp[12] = S[1] ^ S[2] ^ S[6] ^ S[7] ^ S[9] ^ S[11] ^ S[12]; temp[13] = S[0] ^ S[3] ^ S[6] ^ S[7] ^ S[8] ^ S[10] ^ S[13]; temp[14] = S[0] ^ S[3] ^ S[4] ^ S[5] ^ S[9] ^ S[11] ^ S[14]; temp[15] = S[1] ^ S[2] ^ S[4] ^ S[5] ^ S[8] ^ S[10] ^ S[15]; for (i = 0; i < 16; i += 4) { S[i] = temp[i]; S[i + 1] = temp[i + 1]; S[i + 2] = temp[i + 2]; S[i + 3] = temp[i + 3]; } } void Masking_RoundKeyGeneration(u8 W[], u8 RK[], int keysize) { u32 temp[16]; /* W0 = temp[0] ~ temp[3]; W1 = temp[4] ~ temp[7]; W2 = temp[8] ~ temp[11]; W3 = temp[12] ~ temp[15] */ u32 result[4]; u8 masktemp; int i; for (i = 0; i < 64; i += 4) temp[i / 4] = u4byte_in(W + i); // ek1 // (W0) XOR (W1 >> 19) XOR (m'' >> 3)16 result[0] = (temp[7] << 13) ^ (temp[4] >> 19) ^ temp[0]; result[1] = (temp[4] << 13) ^ (temp[5] >> 19) ^ temp[1]; result[2] = (temp[5] << 13) ^ (temp[6] >> 19) ^ temp[2]; result[3] = (temp[6] << 13) ^ (temp[7] >> 19) ^ temp[3]; u4byte_out(RK, result[0]); u4byte_out(RK + 4, result[1]); u4byte_out(RK + 8, result[2]); u4byte_out(RK + 12, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[0] ^= masktemp; RK[1] ^= masktemp; RK[2] ^= masktemp; RK[3] ^= masktemp; RK[4] ^= masktemp; RK[5] ^= masktemp; RK[6] ^= masktemp; RK[7] ^= masktemp; RK[8] ^= masktemp; RK[9] ^= masktemp; RK[10] ^= masktemp; RK[11] ^= masktemp; RK[12] ^= masktemp; RK[13] ^= masktemp; RK[14] ^= masktemp; RK[15] ^= masktemp; // ek2 // (W1) XOR (W2 >> 19) XOR (m'' >> 3)16 result[0] = (temp[11] << 13) ^ (temp[8] >> 19) ^ temp[4]; result[1] = (temp[8] << 13) ^ (temp[9] >> 19) ^ temp[5]; result[2] = (temp[9] << 13) ^ (temp[10] >> 19) ^ temp[6]; result[3] = (temp[10] << 13) ^ (temp[11] >> 19) ^ temp[7]; u4byte_out(RK + 16, result[0]); u4byte_out(RK + 20, result[1]); u4byte_out(RK + 24, result[2]); u4byte_out(RK + 28, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[16] ^= masktemp; RK[17] ^= masktemp; RK[18] ^= masktemp; RK[19] ^= masktemp; RK[20] ^= masktemp; RK[21] ^= masktemp; RK[22] ^= masktemp; RK[23] ^= masktemp; RK[24] ^= masktemp; RK[25] ^= masktemp; RK[26] ^= masktemp; RK[27] ^= masktemp; RK[28] ^= masktemp; RK[29] ^= masktemp; RK[30] ^= masktemp; RK[31] ^= masktemp; // ek3 // (W2) XOR (W3 >> 19) XOR (m'' >> 3)16 result[0] = (temp[15] << 13) ^ (temp[12] >> 19) ^ temp[8]; result[1] = (temp[12] << 13) ^ (temp[13] >> 19) ^ temp[9]; result[2] = (temp[13] << 13) ^ (temp[14] >> 19) ^ temp[10]; result[3] = (temp[14] << 13) ^ (temp[15] >> 19) ^ temp[11]; u4byte_out(RK + 32, result[0]); u4byte_out(RK + 36, result[1]); u4byte_out(RK + 40, result[2]); u4byte_out(RK + 44, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[32] ^= masktemp; RK[33] ^= masktemp; RK[34] ^= masktemp; RK[35] ^= masktemp; RK[36] ^= masktemp; RK[37] ^= masktemp; RK[38] ^= masktemp; RK[39] ^= masktemp; RK[40] ^= masktemp; RK[41] ^= masktemp; RK[42] ^= masktemp; RK[43] ^= masktemp; RK[44] ^= masktemp; RK[45] ^= masktemp; RK[46] ^= masktemp; RK[47] ^= masktemp; // ek4 // (W3) XOR (W0 >> 19) XOR (m'' >> 3)16 result[0] = (temp[3] << 13) ^ (temp[0] >> 19) ^ temp[12]; result[1] = (temp[0] << 13) ^ (temp[1] >> 19) ^ temp[13]; result[2] = (temp[1] << 13) ^ (temp[2] >> 19) ^ temp[14]; result[3] = (temp[2] << 13) ^ (temp[3] >> 19) ^ temp[15]; u4byte_out(RK + 48, result[0]); u4byte_out(RK + 52, result[1]); u4byte_out(RK + 56, result[2]); u4byte_out(RK + 60, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[48] ^= masktemp; RK[49] ^= masktemp; RK[50] ^= masktemp; RK[51] ^= masktemp; RK[52] ^= masktemp; RK[53] ^= masktemp; RK[54] ^= masktemp; RK[55] ^= masktemp; RK[56] ^= masktemp; RK[57] ^= masktemp; RK[58] ^= masktemp; RK[59] ^= masktemp; RK[60] ^= masktemp; RK[61] ^= masktemp; RK[62] ^= masktemp; RK[63] ^= masktemp; // ek5 // (W0) XOR (W1 >> 31) XOR (m'' >> 7)16 result[0] = (temp[7] << 1) ^ (temp[4] >> 31) ^ temp[0]; result[1] = (temp[4] << 1) ^ (temp[5] >> 31) ^ temp[1]; result[2] = (temp[5] << 1) ^ (temp[6] >> 31) ^ temp[2]; result[3] = (temp[6] << 1) ^ (temp[7] >> 31) ^ temp[3]; u4byte_out(RK + 64, result[0]); u4byte_out(RK + 68, result[1]); u4byte_out(RK + 72, result[2]); u4byte_out(RK + 76, result[3]); masktemp = (mask[2] << 1) ^ (mask[2] >> 7); RK[64] ^= masktemp; RK[65] ^= masktemp; RK[66] ^= masktemp; RK[67] ^= masktemp; RK[68] ^= masktemp; RK[69] ^= masktemp; RK[70] ^= masktemp; RK[71] ^= masktemp; RK[72] ^= masktemp; RK[73] ^= masktemp; RK[74] ^= masktemp; RK[75] ^= masktemp; RK[76] ^= masktemp; RK[77] ^= masktemp; RK[78] ^= masktemp; RK[79] ^= masktemp; // ek6 // (W1) XOR (W2 >> 31) XOR (m'' >> 7)16 result[0] = (temp[11] << 1) ^ (temp[8] >> 31) ^ temp[4]; result[1] = (temp[8] << 1) ^ (temp[9] >> 31) ^ temp[5]; result[2] = (temp[9] << 1) ^ (temp[10] >> 31) ^ temp[6]; result[3] = (temp[10] << 1) ^ (temp[11] >> 31) ^ temp[7]; u4byte_out(RK + 80, result[0]); u4byte_out(RK + 84, result[1]); u4byte_out(RK + 88, result[2]); u4byte_out(RK + 92, result[3]); masktemp = (mask[2] << 1) ^ (mask[2] >> 7); RK[80] ^= masktemp; RK[81] ^= masktemp; RK[82] ^= masktemp; RK[83] ^= masktemp; RK[84] ^= masktemp; RK[85] ^= masktemp; RK[86] ^= masktemp; RK[87] ^= masktemp; RK[88] ^= masktemp; RK[89] ^= masktemp; RK[90] ^= masktemp; RK[91] ^= masktemp; RK[92] ^= masktemp; RK[93] ^= masktemp; RK[94] ^= masktemp; RK[95] ^= masktemp; // ek7 // (W2) XOR (W3 >> 31) XOR (m'' >> 7)16 result[0] = (temp[15] << 1) ^ (temp[12] >> 31) ^ temp[8]; result[1] = (temp[12] << 1) ^ (temp[13] >> 31) ^ temp[9]; result[2] = (temp[13] << 1) ^ (temp[14] >> 31) ^ temp[10]; result[3] = (temp[14] << 1) ^ (temp[15] >> 31) ^ temp[11]; u4byte_out(RK + 96, result[0]); u4byte_out(RK + 100, result[1]); u4byte_out(RK + 104, result[2]); u4byte_out(RK + 108, result[3]); masktemp = (mask[2] << 1) ^ (mask[2] >> 7); RK[96] ^= masktemp; RK[97] ^= masktemp; RK[98] ^= masktemp; RK[99] ^= masktemp; RK[100] ^= masktemp; RK[101] ^= masktemp; RK[102] ^= masktemp; RK[103] ^= masktemp; RK[104] ^= masktemp; RK[105] ^= masktemp; RK[106] ^= masktemp; RK[107] ^= masktemp; RK[108] ^= masktemp; RK[109] ^= masktemp; RK[110] ^= masktemp; RK[111] ^= masktemp; // ek8 // (W3) XOR (W0 >> 31) XOR (m'' >> 7)16 result[0] = (temp[3] << 1) ^ (temp[0] >> 31) ^ temp[12]; result[1] = (temp[0] << 1) ^ (temp[1] >> 31) ^ temp[13]; result[2] = (temp[1] << 1) ^ (temp[2] >> 31) ^ temp[14]; result[3] = (temp[2] << 1) ^ (temp[3] >> 31) ^ temp[15]; u4byte_out(RK + 112, result[0]); u4byte_out(RK + 116, result[1]); u4byte_out(RK + 120, result[2]); u4byte_out(RK + 124, result[3]); masktemp = (mask[2] << 1) ^ (mask[2] >> 7); RK[112] ^= masktemp; RK[113] ^= masktemp; RK[114] ^= masktemp; RK[115] ^= masktemp; RK[116] ^= masktemp; RK[117] ^= masktemp; RK[118] ^= masktemp; RK[119] ^= masktemp; RK[120] ^= masktemp; RK[121] ^= masktemp; RK[122] ^= masktemp; RK[123] ^= masktemp; RK[124] ^= masktemp; RK[125] ^= masktemp; RK[126] ^= masktemp; RK[127] ^= masktemp; // ek9 // (W0) XOR (W1 << 61) XOR (m'' << 5)16 result[0] = (temp[5] << 29) ^ (temp[6] >> 3) ^ temp[0]; result[1] = (temp[6] << 29) ^ (temp[7] >> 3) ^ temp[1]; result[2] = (temp[7] << 29) ^ (temp[4] >> 3) ^ temp[2]; result[3] = (temp[4] << 29) ^ (temp[5] >> 3) ^ temp[3]; u4byte_out(RK + 128, result[0]); u4byte_out(RK + 132, result[1]); u4byte_out(RK + 136, result[2]); u4byte_out(RK + 140, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[128] ^= masktemp; RK[129] ^= masktemp; RK[130] ^= masktemp; RK[131] ^= masktemp; RK[132] ^= masktemp; RK[133] ^= masktemp; RK[134] ^= masktemp; RK[135] ^= masktemp; RK[136] ^= masktemp; RK[137] ^= masktemp; RK[138] ^= masktemp; RK[139] ^= masktemp; RK[140] ^= masktemp; RK[141] ^= masktemp; RK[142] ^= masktemp; RK[143] ^= masktemp; // ek10 // (W1) XOR (W2 << 61) XOR (m'' << 5)16 result[0] = (temp[9] << 29) ^ (temp[10] >> 3) ^ temp[4]; result[1] = (temp[10] << 29) ^ (temp[11] >> 3) ^ temp[5]; result[2] = (temp[11] << 29) ^ (temp[8] >> 3) ^ temp[6]; result[3] = (temp[8] << 29) ^ (temp[9] >> 3) ^ temp[7]; u4byte_out(RK + 144, result[0]); u4byte_out(RK + 148, result[1]); u4byte_out(RK + 152, result[2]); u4byte_out(RK + 156, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[144] ^= masktemp; RK[145] ^= masktemp; RK[146] ^= masktemp; RK[147] ^= masktemp; RK[148] ^= masktemp; RK[149] ^= masktemp; RK[150] ^= masktemp; RK[151] ^= masktemp; RK[152] ^= masktemp; RK[153] ^= masktemp; RK[154] ^= masktemp; RK[155] ^= masktemp; RK[156] ^= masktemp; RK[157] ^= masktemp; RK[158] ^= masktemp; RK[159] ^= masktemp; // ek11 // (W2) XOR (W3 << 61) XOR (m'' << 5)16 result[0] = (temp[13] << 29) ^ (temp[14] >> 3) ^ temp[8]; result[1] = (temp[14] << 29) ^ (temp[15] >> 3) ^ temp[9]; result[2] = (temp[15] << 29) ^ (temp[12] >> 3) ^ temp[10]; result[3] = (temp[12] << 29) ^ (temp[13] >> 3) ^ temp[11]; u4byte_out(RK + 160, result[0]); u4byte_out(RK + 164, result[1]); u4byte_out(RK + 168, result[2]); u4byte_out(RK + 172, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[160] ^= masktemp; RK[161] ^= masktemp; RK[162] ^= masktemp; RK[163] ^= masktemp; RK[164] ^= masktemp; RK[165] ^= masktemp; RK[166] ^= masktemp; RK[167] ^= masktemp; RK[168] ^= masktemp; RK[169] ^= masktemp; RK[170] ^= masktemp; RK[171] ^= masktemp; RK[172] ^= masktemp; RK[173] ^= masktemp; RK[174] ^= masktemp; RK[175] ^= masktemp; // ek12 // (W3) XOR (W0 << 61) XOR (m'' << 5)16 result[0] = (temp[1] << 29) ^ (temp[2] >> 3) ^ temp[12]; result[1] = (temp[2] << 29) ^ (temp[3] >> 3) ^ temp[13]; result[2] = (temp[3] << 29) ^ (temp[0] >> 3) ^ temp[14]; result[3] = (temp[0] << 29) ^ (temp[1] >> 3) ^ temp[15]; u4byte_out(RK + 176, result[0]); u4byte_out(RK + 180, result[1]); u4byte_out(RK + 184, result[2]); u4byte_out(RK + 188, result[3]); masktemp = (mask[2] << 5) ^ (mask[2] >> 3); RK[176] ^= masktemp; RK[177] ^= masktemp; RK[178] ^= masktemp; RK[179] ^= masktemp; RK[180] ^= masktemp; RK[181] ^= masktemp; RK[182] ^= masktemp; RK[183] ^= masktemp; RK[184] ^= masktemp; RK[185] ^= masktemp; RK[186] ^= masktemp; RK[187] ^= masktemp; RK[188] ^= masktemp; RK[189] ^= masktemp; RK[190] ^= masktemp; RK[191] ^= masktemp; // ek13 // (W0) XOR (W1 << 31) XOR (m'' << 7)16 result[0] = (temp[4] << 31) ^ (temp[5] >> 1) ^ temp[0]; result[1] = (temp[5] << 31) ^ (temp[6] >> 1) ^ temp[1]; result[2] = (temp[6] << 31) ^ (temp[7] >> 1) ^ temp[2]; result[3] = (temp[7] << 31) ^ (temp[4] >> 1) ^ temp[3]; u4byte_out(RK + 192, result[0]); u4byte_out(RK + 196, result[1]); u4byte_out(RK + 200, result[2]); u4byte_out(RK + 204, result[3]); masktemp = (mask[2] << 7) ^ (mask[2] >> 1); RK[192] ^= masktemp; RK[193] ^= masktemp; RK[194] ^= masktemp; RK[195] ^= masktemp; RK[196] ^= masktemp; RK[197] ^= masktemp; RK[198] ^= masktemp; RK[199] ^= masktemp; RK[200] ^= masktemp; RK[201] ^= masktemp; RK[202] ^= masktemp; RK[203] ^= masktemp; RK[204] ^= masktemp; RK[205] ^= masktemp; RK[206] ^= masktemp; RK[207] ^= masktemp; if (keysize == 192) { // ek14 // (W1) XOR (W2 << 31) XOR (m'' << 7)16 result[0] = (temp[8] << 31) ^ (temp[9] >> 1) ^ temp[4]; result[1] = (temp[9] << 31) ^ (temp[10] >> 1) ^ temp[5]; result[2] = (temp[10] << 31) ^ (temp[11] >> 1) ^ temp[6]; result[3] = (temp[11] << 31) ^ (temp[8] >> 1) ^ temp[7]; u4byte_out(RK + 208, result[0]); u4byte_out(RK + 212, result[1]); u4byte_out(RK + 216, result[2]); u4byte_out(RK + 220, result[3]); masktemp = (mask[2] << 7) ^ (mask[2] >> 1); RK[208] ^= masktemp; RK[209] ^= masktemp; RK[210] ^= masktemp; RK[211] ^= masktemp; RK[212] ^= masktemp; RK[213] ^= masktemp; RK[214] ^= masktemp; RK[215] ^= masktemp; RK[216] ^= masktemp; RK[217] ^= masktemp; RK[218] ^= masktemp; RK[219] ^= masktemp; RK[220] ^= masktemp; RK[221] ^= masktemp; RK[222] ^= masktemp; RK[223] ^= masktemp; // ek15 // (W2) XOR (W3 << 31) XOR (m'' << 7)16 result[0] = (temp[12] << 31) ^ (temp[13] >> 1) ^ temp[8]; result[1] = (temp[13] << 31) ^ (temp[14] >> 1) ^ temp[9]; result[2] = (temp[14] << 31) ^ (temp[15] >> 1) ^ temp[10]; result[3] = (temp[15] << 31) ^ (temp[12] >> 1) ^ temp[11]; u4byte_out(RK + 224, result[0]); u4byte_out(RK + 228, result[1]); u4byte_out(RK + 232, result[2]); u4byte_out(RK + 236, result[3]); masktemp = (mask[2] << 7) ^ (mask[2] >> 1); RK[224] ^= masktemp; RK[225] ^= masktemp; RK[226] ^= masktemp; RK[227] ^= masktemp; RK[228] ^= masktemp; RK[229] ^= masktemp; RK[230] ^= masktemp; RK[231] ^= masktemp; RK[232] ^= masktemp; RK[233] ^= masktemp; RK[234] ^= masktemp; RK[235] ^= masktemp; RK[236] ^= masktemp; RK[237] ^= masktemp; RK[238] ^= masktemp; RK[239] ^= masktemp; } else if (keysize == 256) { // ek14 // (W1) XOR (W2 << 31) XOR (m'' << 7)16 result[0] = (temp[8] << 31) ^ (temp[9] >> 1) ^ temp[4]; result[1] = (temp[9] << 31) ^ (temp[10] >> 1) ^ temp[5]; result[2] = (temp[10] << 31) ^ (temp[11] >> 1) ^ temp[6]; result[3] = (temp[11] << 31) ^ (temp[8] >> 1) ^ temp[7]; u4byte_out(RK + 208, result[0]); u4byte_out(RK + 212, result[1]); u4byte_out(RK + 216, result[2]); u4byte_out(RK + 220, result[3]); masktemp = (mask[2] << 7) ^ (mask[2] >> 1); RK[208] ^= masktemp; RK[209] ^= masktemp; RK[210] ^= masktemp; RK[211] ^= masktemp; RK[212] ^= masktemp; RK[213] ^= masktemp; RK[214] ^= masktemp; RK[215] ^= masktemp; RK[216] ^= masktemp; RK[217] ^= masktemp; RK[218] ^= masktemp; RK[219] ^= masktemp; RK[220] ^= masktemp; RK[221] ^= masktemp; RK[222] ^= masktemp; RK[223] ^= masktemp; // ek15 // (W2) XOR (W3 << 31) XOR (m'' << 7)16 result[0] = (temp[12] << 31) ^ (temp[13] >> 1) ^ temp[8]; result[1] = (temp[13] << 31) ^ (temp[14] >> 1) ^ temp[9]; result[2] = (temp[14] << 31) ^ (temp[15] >> 1) ^ temp[10]; result[3] = (temp[15] << 31) ^ (temp[12] >> 1) ^ temp[11]; u4byte_out(RK + 224, result[0]); u4byte_out(RK + 228, result[1]); u4byte_out(RK + 232, result[2]); u4byte_out(RK + 236, result[3]); masktemp = (mask[2] << 7) ^ (mask[2] >> 1); RK[224] ^= masktemp; RK[225] ^= masktemp; RK[226] ^= masktemp; RK[227] ^= masktemp; RK[228] ^= masktemp; RK[229] ^= masktemp; RK[230] ^= masktemp; RK[231] ^= masktemp; RK[232] ^= masktemp; RK[233] ^= masktemp; RK[234] ^= masktemp; RK[235] ^= masktemp; RK[236] ^= masktemp; RK[237] ^= masktemp; RK[238] ^= masktemp; RK[239] ^= masktemp; // ek16 // (W3) XOR (W0 << 31) XOR (m'' << 7)16 result[0] = (temp[0] << 31) ^ (temp[1] >> 1) ^ temp[12]; result[1] = (temp[1] << 31) ^ (temp[2] >> 1) ^ temp[13]; result[2] = (temp[2] << 31) ^ (temp[3] >> 1) ^ temp[14]; result[3] = (temp[3] << 31) ^ (temp[0] >> 1) ^ temp[15]; u4byte_out(RK + 240, result[0]); u4byte_out(RK + 244, result[1]); u4byte_out(RK + 248, result[2]); u4byte_out(RK + 252, result[3]); masktemp = (mask[2] << 7) ^ (mask[2] >> 1); RK[240] ^= masktemp; RK[241] ^= masktemp; RK[242] ^= masktemp; RK[243] ^= masktemp; RK[244] ^= masktemp; RK[245] ^= masktemp; RK[246] ^= masktemp; RK[247] ^= masktemp; RK[248] ^= masktemp; RK[249] ^= masktemp; RK[250] ^= masktemp; RK[251] ^= masktemp; RK[252] ^= masktemp; RK[253] ^= masktemp; RK[254] ^= masktemp; RK[255] ^= masktemp; // ek17 // (W0) XOR (W1 << 19) XOR (m'' << 3)16 result[0] = (temp[4] << 19) ^ (temp[5] >> 13) ^ temp[0]; result[1] = (temp[5] << 19) ^ (temp[6] >> 13) ^ temp[1]; result[2] = (temp[6] << 19) ^ (temp[7] >> 13) ^ temp[2]; result[3] = (temp[7] << 19) ^ (temp[4] >> 13) ^ temp[3]; u4byte_out(RK + 256, result[0]); u4byte_out(RK + 260, result[1]); u4byte_out(RK + 264, result[2]); u4byte_out(RK + 268, result[3]); masktemp = (mask[2] << 3) ^ (mask[2] >> 5); RK[256] ^= masktemp; RK[257] ^= masktemp; RK[258] ^= masktemp; RK[259] ^= masktemp; RK[260] ^= masktemp; RK[261] ^= masktemp; RK[262] ^= masktemp; RK[263] ^= masktemp; RK[264] ^= masktemp; RK[265] ^= masktemp; RK[266] ^= masktemp; RK[267] ^= masktemp; RK[268] ^= masktemp; RK[269] ^= masktemp; RK[270] ^= masktemp; RK[271] ^= masktemp; } } /* 모든 W 값들과 라운드 키들은 (m'')16으로 마스킹 된 형태여야 함. */ void Masking_ARIA_KeySchedule_Initialization(u8 MK[], u8 KL[16], u8 KR[16], u8 W[], u8 RK[], int keysize) { u8 temp[16]; int i; if (keysize == 192) { for (i = 0; i < 16; i++) temp[i] = CK1[i]; for (i = 0; i < 16; i++) { CK1[i] = CK2[i]; CK2[i] = CK3[i]; CK3[i] = temp[i]; } } else if (keysize == 256) { for (i = 0; i < 16; i++) temp[i] = CK3[i]; for (i = 0; i < 16; i++) { CK3[i] = CK2[i]; CK2[i] = CK1[i]; CK1[i] = temp[i]; } } /* W0 : (W[0] ~ W[15]) ^ (m'')16 */ W[0] = KL[0] ^ mask[2]; W[1] = KL[1] ^ mask[2]; W[2] = KL[2] ^ mask[2]; W[3] = KL[3] ^ mask[2]; W[4] = KL[4] ^ mask[2]; W[5] = KL[5] ^ mask[2]; W[6] = KL[6] ^ mask[2]; W[7] = KL[7] ^ mask[2]; W[8] = KL[8] ^ mask[2]; W[9] = KL[9] ^ mask[2]; W[10] = KL[10] ^ mask[2]; W[11] = KL[11] ^ mask[2]; W[12] = KL[12] ^ mask[2]; W[13] = KL[13] ^ mask[2]; W[14] = KL[14] ^ mask[2]; W[15] = KL[15] ^ mask[2]; /* KR ^ (m'm'mmmmm'm')2*/ KR[0] ^= mask[1]; KR[1] ^= mask[1]; KR[2] ^= mask[0]; KR[3] ^= mask[0]; KR[4] ^= mask[0]; KR[5] ^= mask[0]; KR[6] ^= mask[1]; KR[7] ^= mask[1]; KR[8] ^= mask[1]; KR[9] ^= mask[1]; KR[10] ^= mask[0]; KR[11] ^= mask[0]; KR[12] ^= mask[0]; KR[13] ^= mask[0]; KR[14] ^= mask[1]; KR[15] ^= mask[1]; /* W1 : W[16] ~ W[31] */ temp[0] = W[0] ^ mask[1] ^ CK1[0]; temp[1] = W[1] ^ mask[1] ^ CK1[1]; temp[2] = W[2] ^ mask[0] ^ CK1[2]; temp[3] = W[3] ^ mask[0] ^ CK1[3]; temp[4] = W[4] ^ mask[1] ^ CK1[4]; temp[5] = W[5] ^ mask[1] ^ CK1[5]; temp[6] = W[6] ^ mask[0] ^ CK1[6]; temp[7] = W[7] ^ mask[0] ^ CK1[7]; temp[8] = W[8] ^ mask[1] ^ CK1[8]; temp[9] = W[9] ^ mask[1] ^ CK1[9]; temp[10] = W[10] ^ mask[0] ^ CK1[10]; temp[11] = W[11] ^ mask[0] ^ CK1[11]; temp[12] = W[12] ^ mask[1] ^ CK1[12]; temp[13] = W[13] ^ mask[1] ^ CK1[13]; temp[14] = W[14] ^ mask[0] ^ CK1[14]; temp[15] = W[15] ^ mask[0] ^ CK1[15]; /* 논문의 그림을 보면 각 라운드에는 추가연산으로 (0000m''m''m''m'')2가 적용되지만 라운드 키를 생성하는 과정에서 연산되는 라운드 함수 내에서는 추가 연산을 적용하지 않는다. */ Masking_SubstLayer(temp, 1); DiffLayer(temp); W[16] = temp[0] ^ KR[0]; W[17] = temp[1] ^ KR[1]; W[18] = temp[2] ^ KR[2]; W[19] = temp[3] ^ KR[3]; W[20] = temp[4] ^ KR[4]; W[21] = temp[5] ^ KR[5]; W[22] = temp[6] ^ KR[6]; W[23] = temp[7] ^ KR[7]; W[24] = temp[8] ^ KR[8]; W[25] = temp[9] ^ KR[9]; W[26] = temp[10] ^ KR[10]; W[27] = temp[11] ^ KR[11]; W[28] = temp[12] ^ KR[12]; W[29] = temp[13] ^ KR[13]; W[30] = temp[14] ^ KR[14]; W[31] = temp[15] ^ KR[15]; /* W2 : W[32] ~ W[47] DiffLayer(SubstLayer(W1 XOR CK2)) XOR W0*/ temp[0] = W[16] ^ mask[0] ^ CK2[0]; temp[1] = W[17] ^ mask[0] ^ CK2[1]; temp[2] = W[18] ^ mask[1] ^ CK2[2]; temp[3] = W[19] ^ mask[1] ^ CK2[3]; temp[4] = W[20] ^ mask[0] ^ CK2[4]; temp[5] = W[21] ^ mask[0] ^ CK2[5]; temp[6] = W[22] ^ mask[1] ^ CK2[6]; temp[7] = W[23] ^ mask[1] ^ CK2[7]; temp[8] = W[24] ^ mask[0] ^ CK2[8]; temp[9] = W[25] ^ mask[0] ^ CK2[9]; temp[10] = W[26] ^ mask[1] ^ CK2[10]; temp[11] = W[27] ^ mask[1] ^ CK2[11]; temp[12] = W[28] ^ mask[0] ^ CK2[12]; temp[13] = W[29] ^ mask[0] ^ CK2[13]; temp[14] = W[30] ^ mask[1] ^ CK2[14]; temp[15] = W[31] ^ mask[1] ^ CK2[15]; Masking_SubstLayer(temp, 2); DiffLayer(temp); W[32] = temp[0] ^ W[0] ^ mask[1]; W[33] = temp[1] ^ W[1] ^ mask[1]; W[34] = temp[2] ^ W[2] ^ mask[0]; W[35] = temp[3] ^ W[3] ^ mask[0]; W[36] = temp[4] ^ W[4] ^ mask[0]; W[37] = temp[5] ^ W[5] ^ mask[0]; W[38] = temp[6] ^ W[6] ^ mask[1]; W[39] = temp[7] ^ W[7] ^ mask[1]; W[40] = temp[8] ^ W[8] ^ mask[1]; W[41] = temp[9] ^ W[9] ^ mask[1]; W[42] = temp[10] ^ W[10] ^ mask[0]; W[43] = temp[11] ^ W[11] ^ mask[0]; W[44] = temp[12] ^ W[12] ^ mask[0]; W[45] = temp[13] ^ W[13] ^ mask[0]; W[46] = temp[14] ^ W[14] ^ mask[1]; W[47] = temp[15] ^ W[15] ^ mask[1]; /* W3 : W[48] ~ W[63] DiffLayer(SubstLayer(W2 XOR CK3)) XOR W1 */ temp[0] = W[32] ^ mask[1] ^ CK3[0]; temp[1] = W[33] ^ mask[1] ^ CK3[1]; temp[2] = W[34] ^ mask[0] ^ CK3[2]; temp[3] = W[35] ^ mask[0] ^ CK3[3]; temp[4] = W[36] ^ mask[1] ^ CK3[4]; temp[5] = W[37] ^ mask[1] ^ CK3[5]; temp[6] = W[38] ^ mask[0] ^ CK3[6]; temp[7] = W[39] ^ mask[0] ^ CK3[7]; temp[8] = W[40] ^ mask[1] ^ CK3[8]; temp[9] = W[41] ^ mask[1] ^ CK3[9]; temp[10] = W[42] ^ mask[0] ^ CK3[10]; temp[11] = W[43] ^ mask[0] ^ CK3[11]; temp[12] = W[44] ^ mask[1] ^ CK3[12]; temp[13] = W[45] ^ mask[1] ^ CK3[13]; temp[14] = W[46] ^ mask[0] ^ CK3[14]; temp[15] = W[47] ^ mask[0] ^ CK3[15]; Masking_SubstLayer(temp, 1); DiffLayer(temp); W[48] = temp[0] ^ W[16] ^ mask[0]; W[49] = temp[1] ^ W[17] ^ mask[0]; W[50] = temp[2] ^ W[18] ^ mask[1]; W[51] = temp[3] ^ W[19] ^ mask[1]; W[52] = temp[4] ^ W[20] ^ mask[1]; W[53] = temp[5] ^ W[21] ^ mask[1]; W[54] = temp[6] ^ W[22] ^ mask[0]; W[55] = temp[7] ^ W[23] ^ mask[0]; W[56] = temp[8] ^ W[24] ^ mask[0]; W[57] = temp[9] ^ W[25] ^ mask[0]; W[58] = temp[10] ^ W[26] ^ mask[1]; W[59] = temp[11] ^ W[27] ^ mask[1]; W[60] = temp[12] ^ W[28] ^ mask[1]; W[61] = temp[13] ^ W[29] ^ mask[1]; W[62] = temp[14] ^ W[30] ^ mask[0]; W[63] = temp[15] ^ W[31] ^ mask[0]; Masking_RoundKeyGeneration(W, RK, keysize); } void Masking_ARIA_ENC(u8 PT[], u8 CT[], int keysize, u8 RK[]) { int Nr = keysize / 32 + 8; int i; u8 temp[16]; /* first input masking with (m'm'mm)4*/ temp[0] = PT[0] ^ mask[1]; temp[1] = PT[1] ^ mask[1]; temp[2] = PT[2] ^ mask[0]; temp[3] = PT[3] ^ mask[0]; temp[4] = PT[4] ^ mask[1]; temp[5] = PT[5] ^ mask[1]; temp[6] = PT[6] ^ mask[0]; temp[7] = PT[7] ^ mask[0]; temp[8] = PT[8] ^ mask[1]; temp[9] = PT[9] ^ mask[1]; temp[10] = PT[10] ^ mask[0]; temp[11] = PT[11] ^ mask[0]; temp[12] = PT[12] ^ mask[1]; temp[13] = PT[13] ^ mask[1]; temp[14] = PT[14] ^ mask[0]; temp[15] = PT[15] ^ mask[0]; for (i = 1; i < Nr; i++) { /* 1 ~ Nr - 1 rounds */ Masking_AddRoundKey(temp, RK + 16 * (i - 1)); Masking_SubstLayer(temp, i); DiffLayer(temp); Masking_AddRoundKey2(temp); } /* last round */ Masking_AddRoundKey(temp, RK + 16 * (i - 1)); Masking_SubstLayer(temp, i); Masking_AddRoundKey(temp, RK + 16 * i); /* taking off masking */ CT[0] = temp[0] ^ mask[1]; CT[1] = temp[1] ^ mask[1]; CT[2] = temp[2] ^ mask[0]; CT[3] = temp[3] ^ mask[0]; CT[4] = temp[4] ^ mask[1]; CT[5] = temp[5] ^ mask[1]; CT[6] = temp[6] ^ mask[0]; CT[7] = temp[7] ^ mask[0]; CT[8] = temp[8] ^ mask[1]; CT[9] = temp[9] ^ mask[1]; CT[10] = temp[10] ^ mask[0]; CT[11] = temp[11] ^ mask[0]; CT[12] = temp[12] ^ mask[1]; CT[13] = temp[13] ^ mask[1]; CT[14] = temp[14] ^ mask[0]; CT[15] = temp[15] ^ mask[0]; } void MaskingSboxComputation() { for (int i = 0; i < 256; i++) { maskS1box[i ^ mask[0]] = S1box[i] ^ mask[1]; maskS2box[i ^ mask[0]] = S2box[i] ^ mask[1]; maskinvS1box[i ^ mask[1]] = inv_S1box[i] ^ mask[0]; maskinvS2box[i ^ mask[1]] = inv_S2box[i] ^ mask[0]; } } int main() { int i; int keysize = 256; u8 PT[16] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; u8 MK[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; u8 KL[16] = { 0x00 }; u8 KR[16] = { 0x00 }; u8 CT[16] = { 0x00 }; u8 W[64] = { 0x00 }; /* enough space for 256-bits key generation */ /* 128-bit : 13 x 16 = 208 */ /* 192-bit : 15 x 16 = 240 */ /* 256-bit : 17 x 16 = 272 */ u8 RK[272] = { 0x00 }; srand(time(NULL)); mask[0] = rand() % 255; mask[1] = rand() % 255; mask[2] = mask[0] ^ mask[1]; printf("Masking : %02x %02x %02x\n", mask[0], mask[1], mask[2]); printf("===============================================================\n"); MaskingSboxComputation(); for (int i = 0; i < 16; i++) { KL[i] = MK[i]; KR[i] = MK[i + 16]; } printf("Plaintext : "); for (int i = 0; i < 16; i++) printf("%02x ", PT[i]); printf("\n"); printf("Masterkey : "); for (int i = 0; i < 32; i++) printf("%02x ", MK[i]); printf("\n================================================================\n"); printf("KL: "); for (int i = 0; i < 16; i++) printf("%02x ", KL[i]); printf("\n"); printf("KR: "); for (int i = 0; i < 16; i++) printf("%02x ", KR[i]); printf("\n"); Masking_ARIA_KeySchedule_Initialization(MK, KL, KR, W, RK, keysize); printf("==========================<Round Keys>==========================\n"); for (int i = 0; i < 272; i++) { if (i % 16 == 0) printf("%2d round key : ", ((i / 16) + 1)); printf("%02x ", RK[i]); if (i % 16 == 15) printf("\n"); } printf("===============================================================\n"); Masking_ARIA_ENC(PT, CT, keysize, RK); printf("Ciphertext: "); for (i = 0; i < 16; i++) printf("%02x ", CT[i]); printf("\n"); return 0; }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> //bzero #define bool int #define true 1 #define false 0 typedef struct Trie{ bool isEnd; struct Trie *children[26]; } Trie; /** Initialize your data structure here. */ Trie* trieCreate() { Trie *ret = malloc(sizeof(Trie)); bzero(ret, sizeof(Trie)); ret->isEnd = 1; return ret; } /** Inserts a word into the trie. */ void trieInsert(Trie* obj, char * word) { int len = strlen(word); int index = 0; for (index = 0; index < len; index++) { if (obj->children[word[index] - 'a'] == NULL){ Trie *node = trieCreate(); obj->children[word[index] - 'a'] = node; }else{ if (index == len - 1){ obj->children[word[index] - 'a']->isEnd = 1; } } obj = obj->children[word[index] - 'a']; } } /** Returns if the word is in the trie. */ bool trieSearch(Trie* obj, char * word) { int len = strlen(word); int index = 0; for (index = 0; index < len; index++) { if (obj->children[word[index] - 'a'] == NULL){ return false; } obj = obj->children[word[index] - 'a']; } if (!obj->isEnd) return false; return true; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool trieStartsWith(Trie* obj, char * prefix) { int len = strlen(prefix); int index = 0; for (index = 0; index < len; index++) { if (obj->children[prefix[index] - 'a'] == NULL){ return false; } obj = obj->children[prefix[index] - 'a']; } return true; } void trieFree(Trie* obj) { /*从上至下开始free的话 下面的指针无法得到释放 需要保存上面的指针然后从后道前逐个释放 递归 释放*/ int index = 0; for(index = 0; index < 26; index++) { if (obj->children[index]) trieFree(obj->children[index]); } free(obj); } /** * Your Trie struct will be instantiated and called as such: */ int main() { Trie* obj = trieCreate(); trieInsert(obj, "app"); trieInsert(obj, "apple"); trieInsert(obj, "bob"); bool param_2 = trieSearch(obj, "apple"); bool param_5 = trieSearch(obj, "app"); bool param_3 = trieStartsWith(obj, "bo"); bool param_4 = trieStartsWith(obj, "boa"); printf(" %d %d %d %d", param_2, param_3, param_4, param_5); trieFree(obj); return 0; }
C
#include <stdio.h> #include <string.h> #define N 100000 char n[N + 1], bg[N + 5], eq[N + 5]; int cntb, cnte, st, flag, cntb4, cnte4, finallen, finallen, len; void gogogo(char x) { if(x == '4' || x == '7') { if(x == '4' && 2 * (cnte - cnte4) < len) { finallen = len; st = cnte; bg[cntb = 0, cntb++] = '7'; cntb4 = cnte4; } if(x == '4' && 2 * cnte4 < len) { eq[cnte++] = '4'; cnte4++; } else if(x == '7' && 2 * (cnte - cnte4) < len) { eq[cnte++] = '7'; } else { flag = 0; } } else if(x < '4') { flag = 0; st = cnte; finallen = len; if(2 * cnte4 < len) { bg[cntb = 0, cntb++] = '4'; cntb4 = cnte4 + 1; } else { bg[cntb = 0, cntb++] = '7'; cntb4 = cnte4; } } else if(x < '7') { flag = 0; if(2 * (cnte - cnte4) < len) { finallen = len; st = cnte; bg[cntb = 0, cntb++] = '7'; cntb4 = cnte4; } } } int main(int argc, char *argv[]) { int i; scanf("%s", n); finallen = len = strlen(n); cntb = cnte = st = 0; flag = 1; if(len&1) { flag = 0; bg[cntb++] = '4'; cntb4++; finallen++; } else { bg[cntb++] = '4'; bg[cntb++] = '4'; cntb4 = 2; finallen += 2; } for(i = 0; i < len; i++) { if(2 * cntb4 < finallen) { bg[cntb++] = '4'; cntb4++; } else { bg[cntb++] = '7'; } if(flag) { gogogo(n[i]); } } eq[cnte++] = '\0'; if(flag) printf("%s", eq); else { eq[st] = '\0'; printf("%s", eq); bg[cntb++] = '\0'; printf("%s", bg); } puts(""); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> struct persona{ char nombre[20]; char ocupacion[20]; int edad; }; struct archivo{ struct persona registros[100]; int cant; }; int main(int argc, char *argv[]) { sem_t *sem = sem_open("semFiles",0); if(sem == SEM_FAILED){ perror("p1 sem_open fails: "); exit(EXIT_FAILURE); } if(sem_wait(sem)== -1){ perror("pSemWait sem_wait fails: "); exit(EXIT_FAILURE); } struct archivo lista; lista.cant =0; FILE *fin = fopen(argv[2], "r"); if (fin == NULL) { perror("Error: "); return EXIT_FAILURE; } while ( fscanf(fin,"%s %s %d", lista.registros[lista.cant].nombre,lista.registros[lista.cant].ocupacion,&lista.registros[lista.cant].edad) == 3) { lista.cant++; } fclose(fin); for(int i=0;i<lista.cant;i++){ printf("%s %s %d\n", lista.registros[i].nombre,lista.registros[i].ocupacion,lista.registros[i].edad); } FILE *fout = fopen(argv[3], "w"); if (fout == NULL) { perror("Error1: "); return EXIT_FAILURE; } for(int a=1;a<lista.cant;a++){ for(int b = lista.cant-1;b>=a;b--){ if(lista.registros[b-1].edad>lista.registros[b].edad){ struct persona temp = lista.registros[b-1]; lista.registros[b-1] = lista.registros[b]; lista.registros[b] = temp; } } } for(int i = 0;i<lista.cant; i++){ fprintf(fout,"%s %s %d\n", lista.registros[i].nombre,lista.registros[i].ocupacion,lista.registros[i].edad); } fclose(fout); if(sem_post(sem)== -1){ perror("pSemCreate sem_wait fails: "); exit(EXIT_FAILURE); } }
C
/* ** EPITECH PROJECT, 2019 ** my_getnbr_v2.c ** File description: ** This file contains a function that do the same things ** that the normal my_getnbr but also verify if their is an error. */ #include <unistd.h> #include "samson.h" int my_getnbr_v2(char const *str, int *error) { int number = 0; int index = 0; if (str[0] == '-' && str[1] != '\0' && str[1] != 'v') { index++; } while (str[index] != '\0') { if (str[index] >= '0' && str[index] <= '9') { number = number * 10; number = number + my_transform_char_into_digit(str[index]); } else if (str[0] == '-' && str[1] == 'v' && str[2] == '\0') { *error = 2; } else *error = 1; index++; } if (str[0] == '-') return (-1 * number); return (number); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> time_t *timep = NULL; char* gettime(){ if(timep == NULL){ timep = malloc(sizeof(time_t)); } time(timep); char *s = ctime(timep); s[strlen(s)-1] = '\0'; return s; } #define __DEBUG__ //#undef __DEBUG__ //屏蔽此行 放开调试 #ifdef __DEBUG__ #define DEBUG(formnt,...) \ fprintf(g_log,"\n\033[31m ERROR \033[0m[%s],filename:[%s],function:[%s()] line:[%d] "formnt, \ gettime(),__FILE__,__FUNCTION__,__LINE__,##__VA_ARGS__) #else #define DEBUG(formnt,...) #endif #define __INFO__ //#undef __INFO__ //屏蔽此行 放开调试 #ifdef __INFO__ #define INFO(format,...) \ fprintf(g_log,"\n\033[31m INFO \033[0m[%s],filename:[%s], function: [%s()], line :[%d]"format, \ gettime(),__FILE__,__FUNCTION__,__LINE__,##__VA_ARGS__) #else #define INFO(format,...) #endif FILE *g_log; int create_list() { DEBUG("begin"); printf("exec create_list\n"); INFO("end"); for(;;){ DEBUG("123"); printf("123"); sleep(1); } return 0; } int main(int ragc,char * argv[]) { int ret = 0; g_log=fopen("/opt/log.txt","a+"); if(g_log == NULL){ printf("open log file failed!\n"); return -1; } DEBUG("begin"); INFO("tel = %s","18792741184"); ret = create_list(); DEBUG("end"); fclose(g_log); g_log = NULL; return 0; }
C
/*----------------------------------------* * Random String Copy/Paste Speed tests * *----------------------------------------*/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <time.h> #include "../../Library/clipboard.h" #define NTESTS 10 /*Defaults to 100MB*/ #define STR_LEN 33 /*Random string generator, implemented as in: https://stackoverflow.com/questions/15767691/ */ void rand_str(char *dest, unsigned length) { char charset[] = "0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; while (--length > 0) { size_t index = (double) rand() / RAND_MAX * (sizeof charset - 1); *(dest++) = charset[index]; } *dest = '\0'; } int compare_str(char * s1,char * s2,size_t length){ if(s1 == NULL || s2 == NULL){ return -1; } else if(s1[length -1] != '\0'){ return -2; } else if(s2[length -1] != '\0'){ return -3; } else return abs(strcmp(s1,s2)); } int main(int argc,char * argv[]){ char * data; char * rcvData; int res; int clip,region; int i = 0; time_t t; if(argc < 2) exit(1); if( (clip = clipboard_connect(argv[1]) )<1){ fprintf(stderr,"Could not connect to clipboard"); return 1; } data = malloc(STR_LEN); if(data == NULL){ printf("Could not allocate memmory for buffer.\n"); exit(-1); } rcvData = malloc(STR_LEN); if(rcvData == NULL){ printf("Could not allocate memmory for buffer.\n"); exit(-2); } printf("\nThis test copies and pastes random strings in a loop,\nchecking if the from paste is the same as the data sent to copy.\n"); printf("\nStarting..\n"); srand((unsigned) time(&t)); for(i = 0; i < NTESTS; i++){ rand_str(data, STR_LEN); region = rand()%10; #ifdef DEBUG printf("Sending %d:\n", clipboard_copy(clip,region,data,STR_LEN)); printf("%s\n",data); printf("Recv %d :\n",clipboard_paste(clip,region,rcvData,STR_LEN)); printf("%s\n",rcvData); #else clipboard_copy(clip,region,data,STR_LEN); clipboard_paste(clip,region,rcvData,STR_LEN); #endif res = compare_str(rcvData,data,STR_LEN); printf("Test %d (region %d): ",i,region); if(res == 0){ printf("OK.\n"); } else if(res == -1){ printf("Error - null string\n"); break; } else if(res == -2){ printf("Error - String 1 is corrupted\n"); break; } else if(res == -3){ printf("Error - String 2 is corrupted\n"); break; } else { printf("Error- String mismatch %d\n",res); break; } } clipboard_close(clip); free(data); free(rcvData); // printf("WAIT: %d\n",clipboard_wait(clip,region,command_data,10000)); }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { pid_t pid = vfork(); int num = 0; switch(pid) { case -1: printf("vfork fail\n"); break; case 0: printf("child:%d\n", getpid()); close(STDIN_FILENO); printf("hase closed STDIN_FILENO\n"); _exit(EXIT_SUCCESS); break; default: printf("parent:%d\n", getpid()); scanf("%d", &num); printf("num=%d\n", num); break; } }
C
#include <stdio.h> #include <math.h> #include <stdbool.h> bool isPrime(int number) { for(int i = 2; i <= sqrt(number); ++i) { if(number % i == 0) return false; } return true; } int main() { for(int i = 1; i <= 100; ++i) { if(isPrime(i)) printf("%d ", i); } return 0; }
C
#include "std.h" int found; reset(arg) { if(!arg) set_light(1); found = 0; } object mimic; int level, wc, ac; string short, name, long; init() { if(!present("qstob", this_player())) { write("You did not go by the right paths!\n"); move_object(this_player(), "/room/church"); return 1; } add_action("east","east"); add_action("west","west"); } east() { level = this_player()->query_level(); short = this_player()->short(); name = this_player()->query_real_name(); if(found == 0) { mimic = clone_object("obj/monster"); mimic->set_name(name); mimic->set_alias("mimic"); mimic->set_level(level); mimic->set_short(short); mimic->set_ac(level/3); mimic->set_wc(level); mimic->set_long(short+"\nSomething doesn't seem right about this person.\n"); call_other(mimic, "set_heal", 1, 15); move_object(clone_object("players/molasar/OBJ/qstob"), mimic); move_object(mimic, this_object()); write("Someone steps out from behind the shadows.\n"); say("Someone steps out from behind the shadows.\n"); found = 1; return 1; } if(present("mimic")) { write("The mimic blocks your passage.\n"); return 1; } this_player()->move_player("east#players/molasar/SEA/cave2"); return 1; } short() { return "Entrance to a cave"; } long() { write("An eerie light from an unknown source provides you with enough\n"); write("illumination to see. A small opening leads to the east.\n"); write(" There are two obvious exits: east and west\n"); } west() { this_player()->move_player("west#players/molasar/SEA/isle_path3"); return 1; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *quelle; int c; char datei[20]; fpos_t pos; printf("Welche Datei wollen Sie oeefnen : "); scanf("%s", datei); if((quelle=fopen(datei, "r")) == NULL){ fprintf(stderr, "Konnte %s nicht oeffnen !!\n", datei); return EXIT_FAILURE; } // fseek(quelle, 0L, SEEK_END); fgetpos(quelle, &pos); printf("Der Positionszeiger zeigt auf Byte : %ld\n", pos); while((c = getc(quelle)) != EOF) putc(c, stdout); printf("Groesse der Datei= Byte : %ld ", ftell(quelle)); // Wir setzten den FILE-Zeiger wieder an den Anfang der Datei fseek(quelle, 0L, SEEK_SET); //fsetpos(quelle, &pos); printf("Wie sind wieder an Position %ld\n", pos); return EXIT_SUCCESS; }
C
#include <stdio.h> int main() { float saA, saB, saC, temp; char salesCode, buff; saA = saB = saC = temp = 0; do { printf("Introducir el monto de la boleta (0 para finalizar): "); scanf("%f", &temp); // Fix to clean buffer scanf("%c", &buff); if (0 != temp) { printf("Introduce el codigo del vendedor (A,B,C): "); scanf("%c", &salesCode); if ('A' == salesCode) { saA += temp; } else if ('B' == salesCode) { saB += temp; } else if ('C' == salesCode) { saC += temp; } else { printf("Agente no encontrado. Factura no asignada.\n"); } } printf("\n----------------------------------------------------\n"); } while (0 != temp); printf("La comision para las ventas del vendedor A es: %.2f\n", saA * 0.05); printf("La comision para las ventas del vendedor B es: %.2f\n", saB * 0.05); printf("La comision para las ventas del vendedor C es: %.2f\n", saC * 0.05); return 0; }
C
#include<stdio.h> int main() { int n; printf("Enter a number :"); scanf("%d",&n); int z; z=0; int y=2; while(y<=n/2) { if(n%y==0) { z=1; break; } y++; } if(z==1) { printf(" not prime number"); } else { printf("prime number"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(void){ printf("int *i = malloc(sizeof(int)); //right\n"); int *i = malloc(sizeof(int)); printf("*i = 23; //right\n"); *i = 23; printf("int *j = 23; //wrong\nwill give a complier warning\n"); printf("warning: incompatible integer to pointer conversion initializing\n"); int *j = 23; printf("It is wrong."); printf("Use the following rul.\n"); printf("When used for a declaration, a star indicates a pointer\n"); printf("When not used as a declaration, a star indicates the value of the pointer\n"); };
C
/** * TCP Client * * @author Sebastian Menski (734272) <menski@uni-potsdam.de> * @author Martin Ohmann (734801) <ohmann@uni-potsdam.de> */ #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <sysexits.h> #include <err.h> #define PORT 10041 #define BUF_SIZE 1024 #define MATNR_MIN 1 #define MATNR_MAX 999999 enum { ERROR = -1, SUCCESS }; int main(int argc, char *argv[]) { int client_sockfd, port, result; int msg_id, mat_nr, rand_nr; struct sockaddr_in server_address; char *addr_string, buf[BUF_SIZE]; /* parse arguments */ if (argc < 3) { errx(EX_USAGE, "Server address and Mat-NR. required\nusage: tcp_client SERVER_ADDR MAT_NR [PORT]"); } addr_string = argv[1]; mat_nr = atoi(argv[2]); if (mat_nr < MATNR_MIN || mat_nr > MATNR_MAX) { errx(EX_USAGE, "MAT_NR must be between %d and %d\nusage: tcp_client SERVER_ADDR MAT_NR [PORT]", MATNR_MIN, MATNR_MAX); } port = argc > 3 ? atoi(argv[3]) : PORT; /* create client socket */ client_sockfd = socket(AF_INET, SOCK_STREAM, 0); if (client_sockfd == ERROR) { err(EX_OSERR, "unable to create socket"); } /* set server address values; */ server_address.sin_family = AF_INET; server_address.sin_addr.s_addr= inet_addr(addr_string); server_address.sin_port = htons(port); /* connect to server */ result = connect(client_sockfd, (struct sockaddr *) &server_address, sizeof(server_address)); if (result == ERROR) { close(client_sockfd); err(EX_OSERR, "unable to connect to address %s:%d", addr_string, port); } /* send first message to server */ result = sprintf(buf, "%d %06d", 1, mat_nr); if (result < 0) { close(client_sockfd); errx(EX_DATAERR, "unable to format message"); } result = write(client_sockfd, buf, result + 1); /* +1 for \0 string terminator */ if (result == ERROR) { close(client_sockfd); err(EX_OSERR, "unable to send message"); } /* read answer from server */ result = read(client_sockfd, buf, BUF_SIZE); if (result == ERROR) { close(client_sockfd); err(EX_OSERR, "unable to read message from server"); } printf("%s: received \"%s\"\n", argv[0], buf); result = sscanf(buf, "%d %d %d", &msg_id, &mat_nr, &rand_nr); if (result != 3) { close(client_sockfd); errx(EX_DATAERR, "parsing error"); } if (msg_id != 2) { close(client_sockfd); errx(EX_DATAERR, "wrong message id from client"); } /* send second message to server */ result = sprintf(buf, "%d %06d %07d", 3, mat_nr, rand_nr); if (result < 0) { close(client_sockfd); errx(EX_DATAERR, "unable to format message"); } result = write(client_sockfd, buf, result + 1); /* +1 for \0 string terminator */ if (result == ERROR) { close(client_sockfd); err(EX_OSERR, "unable to send message"); } /* close socket and exit */ close(client_sockfd); return EX_OK; }
C
#include "pub/osl/inc/osl_timer.h" #include "sdk_timer.h" static int timerHandle = -1; static int count = 0; static unsigned int timerProc(void *p) { // This timer callback function will be executed every second, in the timer thread. // You can do some short-term operations here, // but don't block it all the time, which will affect the scheduling of the system's tasks. count ++; return 0; } // int sdk_timer_get_count() { // You can call this function in the ui thread to read, the number of executions of the timer thread return count ; } void sdk_timer_init() { if(timerHandle == -1){ // Create a timer timerHandle = osl_TimerCreate(timerProc, 0 , 1000, TIMER_MODE_NORMAL , 0); osl_TimerEnable(timerHandle); // Start this timer } }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: 0783170 * * Created on 31 de Agosto de 2017, 09:32 */ #include <stdio.h> #include <stdlib.h> /* * */ int main(int argc, char** argv) { int num; printf("digite um numero:"); scanf("%d", &num); printf("O numero %d eh", num); if (num % 2 == 0) printf(" par"); else printf(" impar"); if (num < 0) printf(" e negativo."); else printf(" e positivo"); return (EXIT_SUCCESS); }
C
#include "all.h" void erase(LIST start, int a) { int result=0; result=delete(start,a);//calling delete function to delete the numbe if(result==0)//function will return 0 if it did not found the number in the list { printf("NODE NOT FOUND\n"); } if(result==1)//function wil return 1 if it is successfully delete the number { printf("SUCCESS\n"); } return; }
C
#ifndef _BUFFER_H #define _BUFFER_H #include <stdint.h> #define BUFFER_SIZE (1024) /** * Allocate a piece of the dynamic memory buffer. * * A buffer allocated this way is valid until all dynamic buffers are * flushed using buffer_release_all(). * * @param length amount of bytes to allocate. For aligment reasons, the * length is rounded up to the next multiple of four. * @return pointer to the buffer, or NULL if not enough space is left * in the dynamic memory heap */ void *buffer_alloc(const uint16_t length); /** * Release and invalidate all pointers acquired through buffer_alloc(). */ void buffer_release_all(); #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: zhasni <zhasni@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/16 16:31:33 by zhasni #+# #+# */ /* Updated: 2015/04/02 21:22:06 by zhasni ### ########.fr */ /* */ /* ************************************************************************** */ #include "ftp.h" void ft_get_env(t_env *env, char **envp) { int i; int lentab; i = 0; lentab = ft_tablen(envp); if (!(env->bkp = malloc(sizeof(char *) * lentab))) return ; while (envp[i]) { env->bkp[i] = ft_strdup(envp[i]); i++; } env->bkp[i] = NULL; env->oldpwd = ft_get_line_env(env, "OLDPWD"); return ; } int ft_replace_line_env(t_env *env, char *key, char *newpath) { int index; int i; char *tmp; index = 0; while (env->bkp[index]) { i = 0; while (env->bkp[i] && key[i] && key[i] == env->bkp[index][i]) i++; if (env->bkp[index][i] == '=') { tmp = ft_my_join(key, "="); env->bkp[index] = ft_my_join(tmp, newpath); return (1); } index++; } return (0); } char *ft_get_line_env(t_env *env, char *key) { int index; int i; index = 0; while (env->bkp[index]) { i = 0; while (env->bkp[i] && key[i] && key[i] == env->bkp[index][i]) i++; if (env->bkp[index][i] == '=') return (&env->bkp[index][i + 1]); index++; } return (NULL); }
C
/* * ===================================================================================== * * Filename: http_download.h * * Description: HTTP下载器 * * Version: 1.0 * Created: 2014年05月28日 12时09分14秒 * Revision: none * Compiler: gcc * * Author: 聂汉子 (niehanzi), niehanzi@qiyi.com * Company: 奇艺世纪 * * ===================================================================================== */ #ifndef _HTTP_DOWNLOAD_H_ #define _HTTP_DOWNLOAD_H_ #include <stdio.h> typedef struct _http_buffer_t { char *buffer; //存放HTTP请求返回内容 size_t buffer_size; //buffer的总的大小 size_t size; //内容的实际大小 } http_buffer_t; typedef struct _http_file_t { FILE *fp; size_t size; } http_file_t; /** * Name: http_init * Description: HTTP初始化全局资源。 * Parameter: * Return: */ void http_init(); /** * Name: http_close * Description: HTTP释放全局资源。 * Parameter: * Return: */ void http_close(); /** * Name: http_download_to_disk * Description: 通过http将文件下载的硬盘。 * Parameter: url -> 下载地址; * file -> 下载后保存地址; * download_speed -> 下载文件的速度, 单位K * Return: 返回结果状态 * 0 -> 下载失败 * 1 -> 下载成功 */ int http_download_to_disk(char *url, char *file, float *download_speed); /** * Name: http_download_to_disk2 * Description: 通过http将文件下载的硬盘, 可以重试times次。 * Parameter: url -> 下载地址. * file -> 下载后保存地址. * times -> 下载失败重试的次数. * retry -> 是否继续重试下载 * download_speed -> 下载速度,单位K * Return: 返回结果状态 * 0 -> 下载失败 * 1 -> 下载成功 */ int http_download_to_disk2(char *url, char *file, int times, int *retry, float *download_speed); /** * Name: http_download_to_memory * Description: 通过http将下载的内容保存到内存中。 * Parameter: url -> 下载地址; * buffer -> 下载内容的buffer; * size -> 传入buffer大小。 * Return: 0 -> 下载失败 * 1 -> 下载成功 */ int http_download_to_memory(char *url, char *buffer, int size); /** * Name: http_download_to_memory2 * Description: 通过http将下载的内容保存到内存中, 可以重试times次。 * Parameter: url -> 下载地址; * buffer -> 下载内容的buffer; * size -> 传入buffer大小。 * times -> 下载失败重试的次数。 * retry -> 是否终止重试下载 * Return: 0 -> 下载失败 * 1 -> 下载成功 */ int http_download_to_memory2(char *url, char *buffer, int size, int times, int *retry); #endif
C
/*Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdbool.h> char* addStrings(char* num1, char* num2) { int count = 0; int carry = 0; int add = 0; char *ret = calloc(1,sizeof(char)); memset(ret,0,sizeof(char)); int len1 = strlen(num1); int len2 = strlen(num2); if (len1 >= len2) { for (int i = len1 - 1;i >= 0;i--) { ret = realloc(ret, (count + 2) * sizeof(char)); memmove(ret + 1, ret, (count + 1) * sizeof(char)); if (count<len2) { add = (num1[i] - '0' + num2[len2 - 1 - count] - '0') + carry; carry = add / 10; ret[0] = add - 10 * carry + '0'; count++; } else { add = num1[i] - '0' + carry; carry = add / 10; ret[0] = add - 10 * carry + '0'; count++; } } if (carry != 0) { ret = realloc(ret, (count + 2) * sizeof(char)); memmove(ret + 1, ret, (count + 1) * sizeof(char)); ret[0] = carry + '0'; } return ret; } else { return addStrings(num2, num1); } } int main(int argc, char const *argv[]) { char *s=NULL; printf("%s\n", addStrings("999999","191")); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "primality_test.h" #define NUMERO_COMPOSTO 0 #define NUMERO_PRIMO 1 #define DEBUG 1 int main(int argc, char *argv[]) { char *mode = argv[1]; if (!strcmp(mode, "deterministico")) { int64 n = (int64) atoi(argv[2]); puts(test_deterministico(n) == NUMERO_PRIMO ? "NUMERO PRIMO" : "NUMERO COMPOSTO"); } else if (!strcmp(mode, "fermat_singola_base")) { int64 n = (int64) atoi(argv[2]); int64 a = (int64) atoi(argv[3]); puts(fermat_singola_base(n, a) == NUMERO_PRIMO ? "NUMERO PRIMO" : "NUMERO COMPOSTO"); } else if (!strcmp(mode, "fermat")) { int64 n = (int64) atoi(argv[2]); puts(test_fermat(n) == NUMERO_PRIMO ? "NUMERO PRIMO" : "NUMERO COMPOSTO"); } else if (!strcmp(mode, "miller_singola_base")) { int64 n = (int64) atoi(argv[2]); int64 a = (int64) atoi(argv[3]); puts(miller_rabin_singola_base(n, a) == NUMERO_PRIMO ? "NUMERO PRIMO" : "NUMERO COMPOSTO"); } else if (!strcmp(mode, "miller_regolare")) { int64 n = (int64) atoi(argv[2]); puts(miller_rabin_regolare(n) == NUMERO_PRIMO ? "NUMERO PRIMO" : "NUMERO COMPOSTO"); } else if (!strcmp(mode, "miller_probabilistico")) { int64 n = (int64) atoi(argv[2]); int64 precisione = (int64) atoi(argv[3]); puts(miller_rabin_probabilistico(n, precisione) == NUMERO_PRIMO ? "NUMERO PRIMO" : "NUMERO COMPOSTO"); } else if (!strcmp(mode, "miller_test_errori")) { int64 n = (int64) atoi(argv[2]); int classe = test_deterministico(n); // Scelgo il valore di a for (int i = 2; i < (n - 1); i++) { if (miller_rabin_singola_base(n,i) != classe) { printf("Errore con n = %d e a = %d \n", n, i); } } } return 0; }
C
/// \file main.h /// ESTC 5-th laboratory work (example). #include "main.h" /// \brief onboard help LEDs u16 onboard_leds[3]; /// \brief current color u8 color; /// \brief colors u8 red, green, blue; /// \brief debounce params u32 systime, timeout_color, timeout_brightness; /// \brief Entry point int main(void) { AllInit(); color = 0; red = 0; green = 0; blue = 0; onboard_leds[0] = GPIO_Pin_14; onboard_leds[1] = GPIO_Pin_12; onboard_leds[2] = GPIO_Pin_15; DebounceLaunch(); ESTC_InitExBoardAndRunPWM(); GPIO_SetBits(GPIOD, onboard_leds[color]); ESTC_ExBoardLedsSetColorHEX(0x4B0082); while (1); } void EXTI0_IRQHandler(void) { if (EXTI_GetITStatus(EXTI_Line0) != RESET) { EXTI_ClearITPendingBit(EXTI_Line0); if (timeout_brightness) return; GPIO_ResetBits(GPIOD, onboard_leds[color]); color = (color + 1) % 3; GPIO_SetBits(GPIOD, onboard_leds[color]); timeout_brightness = systime; } } void EXTI1_IRQHandler(void) { if (EXTI_GetITStatus(EXTI_Line1) != RESET) { EXTI_ClearITPendingBit(EXTI_Line1); if (timeout_color) return; if (color == 0) red = (red + 16) % 256; else if (color == 1) green = (green + 16) % 256; else if (color == 2) blue = (blue + 16) % 256; ESTC_ExBoardLedsSetColorRGB(red,green,blue); timeout_color = systime; } } void DebounceLaunch(void) { RCC_ClocksTypeDef RCC_Clocks; RCC_GetClocksFreq(&RCC_Clocks); systime = 0; timeout_color = 0; timeout_brightness = 0; (void)SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000); } void SysTick_Handler(void) { systime++; if (timeout_color && systime - timeout_color > 100) timeout_color = 0; if (timeout_brightness && systime - timeout_brightness > 100) timeout_brightness = 0; }
C
#include <iostream> #include <vector> #include <numeric> #include <string> #include <functional> int main() { std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = std::accumulate(v.begin(), v.end(), 0); int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>()); auto dash_fold = [](std::string a, int b) { return std::move(a) + '-' + std::to_string(b); }; std::string s = std::accumulate(std::next(v.begin()), v.end(), std::to_string(v[0]), // start with first element dash_fold); // Right fold using reverse iterators std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(), std::to_string(v.back()), // start with last element dash_fold); std::cout << "sum: " << sum << '\n' << "product: " << product << '\n' << "dash-separated string: " << s << '\n' << "dash-separated string (right-folded): " << rs << '\n'; }
C
/************************************************************************* > File Name: commom.c > Author:yangkun > Mail:yangkungetit@163.com > Created Time: Wed 20 Dec 2017 02:27:34 PM CST ************************************************************************/ #include"commom.h" key_t getkey() { key_t key=ftok(PATH,PRO_ID); if(key==-1) { perror("ftok"); exit(1); } return key; } int getshm(key_t key,int flag,int size) { int ret=shmget(key,size,flag); if(ret==-1) { perror("shmget"); exit(1); } return ret; } int createshm(int size) { return getshm(getkey(),IPC_CREAT | IPC_EXCL | 0666,size); } int getshmid() { return getshm(getkey(),IPC_CREAT,0); } void destory(int id) { int ret=shmctl(id,IPC_RMID,NULL); if(ret==-1) { perror("shmctl"); exit(1); } printf("successful\n"); } char* connection(int shmid) { char* ptr=(char*)shmat(shmid,NULL,0); if(*(int*)ptr==-1) { perror("shmat"); exit(1); } return ptr; } void disconnection(void* ptr) { int ret=shmdt(ptr); if(ret==-1) { perror("shmdt"); exit(1); } printf("disconnecte successfully\n"); }
C
#include<stdio.h> void computeArray1(int a[], int b[], int n) { int i, j, product=1; for (i = 0; i < n; i++){ for (j = 0; j < n; j++) { if(i!=j && a[j]!=0) product *= a[j]; } b[i] = product; } } void computeArray2(int a[], int b[], int n) { int product = 1, i; for (i = 0; i < n; i++) if(a[i] !=0) product *= a[i]; for (i = 0; i < n; i++) if (a[i] != 0) b[i] = product / a[i]; else b[i] = product; } void computeArray3(int a[], int b[], int n) { int lma[10], rma[10], i; lma[0] = a[0]; rma[n - 1] = a[n - 1]; for (i = 1; i < n; i++) { lma[i] = lma[i - 1] * a[i]; rma[(n - 1) - i] = rma[n - i] * a[n - 1 - i]; } for (i = 1; i < n - 1; i++) { b[i] = lma[i - 1] * rma[i + 1]; } b[0] = rma[1]; b[n - 1] = lma[n - 2]; } void computeArray4(int a[], int b[], int n) { int lma[10], i; lma[0] = a[0]; b[n - 1] = a[n - 1]; for (i = 1; i < n; i++) { lma[i] = lma[i - 1] * a[i]; b[(n - 1) - i] = b[n - i] * a[n - 1 - i]; } b[0] = b[1]; for (i = 1; i < n - 1; i++) { b[i] = lma[i - 1] * b[i + 1]; } b[n - 1] = lma[n - 2]; } void computeArray5(int a[], int b[], int n) { int i, lm = a[0]; b[n - 1] = a[n - 1]; for (i = 1; i < n; i++) { b[(n - 1) - i] = b[n - i] * a[n - 1 - i]; } b[0] = b[1]; for (i = 1; i < n - 1; i++) { b[i] = lm * b[i + 1]; lm *= a[i]; } b[n - 1] = lm; } main() { int a[10], b[10], i, n; scanf_s("%d", &n); for ( i = 0; i < n; i++) { scanf_s("%d", &a[i]); } computeArray5(a, b, n); for (i = 0; i < n; i++) printf("%d ", b[i]); _getch(); }
C
#include <stdio.h> int main() { int numero; char resposta; scanf("%d", &numero); if (numero % 5 == 0) { resposta = 'S'; } else { resposta = 'N'; } printf("%c\n", resposta); return 0; }
C
/* ** EPITECH PROJECT, 2021 ** bsqRematered ** File description: ** step_checking */ #include "../../../includes/bsq_func.h" static ksize_t get_curr_max_size(bsq_manager_t *manager, ksize_t x, ksize_t y) { ksize_t max_x = length(manager->square[0]) - x; ksize_t max_y = length_text(manager->square) - y; if (max_x < max_y) return max_x; return max_y; } static bool check_can_do(cstring line, ksize_t x, ksize_t i) { for (ksize_t _x = x; _x < x + i; _x++) { if (line[_x] != '.') return false; } return true; } static bool can_do_it(bsq_manager_t *manager, ksize_t x, ksize_t y, ksize_t i) { for (ksize_t _y = y; _y < y + i; _y++) { if (!check_can_do(manager->square[_y], x, i)) { return false; } } return true; } void step_checking(bsq_manager_t *manager, ksize_t x, ksize_t y) { ksize_t max_size = get_curr_max_size(manager, x, y) + 1; ksize_t curr_size = 0; for (ksize_t i = 1; i < max_size; i++) { if (!can_do_it(manager, x, y, i)) break; curr_size = i; } manager->current.size = curr_size; manager->current.pos.x = x; manager->current.pos.y = y; }
C
#ifndef SEM_H #define SEM_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/sem.h> #include <unistd.h> struct semun { int val; struct semid_ds *buf; ushort *array; }; static int semid = 0; void initsem(key_t key,int nsems) { semid = semget(key,nsems,IPC_CREAT | IPC_EXCL| 0600); if(semid == -1) { semid = semget(key,nsems,IPC_CREAT | 0600); if(semid == -1) { printf("semget error"); } } else { struct semun a;//a pass value a.val = 1; if(semctl(semid,0,SETVAL,a)==-1)//0 represents the semaphore table { perror("semctl init error"); } } } void sem_p() { struct sembuf buf; buf.sem_num = 0;//Semaphore subscript buf.sem_op = -1;//p operation buf.sem_flg = SEM_UNDO; if(semop(semid,&buf,1)==-1) { perror("p error"); } } void sem_v() { struct sembuf buf; buf.sem_num = 0; buf.sem_op = 1; buf.sem_flg = SEM_UNDO;//Set the semaphore value to automatically recover when the process has an error to prevent a process from occupying the semaphore if(semop(semid,&buf,1)==-1)//1 represents the operand, the number of sembuf { perror("v error"); } } void sem_destroy() { if(semctl(semid,0,IPC_RMID)==-1)//0 represents the semaphore set { perror("semctl destroy error"); } printf("\n End process press to continue ..."); } #endif
C
#include<stdio.h> int main(void) { int i; for(i=1; i<101; i++) { //print num if not divisible by 3 or 5 if ( i%3 != 0 && i%5 != 0 ) printf("%i",i); //print fizz if divisible by 3 and buzz if divisible by 5 else { if ( i%3 == 0 ) printf("fizz"); if ( i%5 == 0 ) printf("buzz"); } //new line for each number printf("\n"); } return 0; }
C
#include "bmp.h" #include <stdio.h> #include <stdlib.h> size_t getGap1Size(BMP* image) { return image->bmpFileHeader->bfOffBits - sizeof(BITMAPFILEHEADER) - sizeof(BITMAPINFO); } size_t getPadding(BMP* image) { return ((4 - image->bmpInfo->biWidth % 4) % 4); } size_t getPixelDataSize(BMP* image) { return image->bmpInfo->biHeight * (image->bmpInfo->biWidth + getPadding(image)); } BMP* readBMP(char* filepath) { FILE* BMPFile = fopen(filepath, "rb"); if (BMPFile == NULL) return NULL; BMP* image = malloc(sizeof(BMP)); image->bmpFileHeader = malloc(sizeof(BITMAPFILEHEADER)); image->bmpInfo = malloc(sizeof(BITMAPINFO)); fread(image->bmpFileHeader, sizeof(BITMAPFILEHEADER), 1, BMPFile); fread(image->bmpInfo, sizeof(BITMAPINFO), 1, BMPFile); image->gap1 = malloc(getGap1Size(image)); fread(image->gap1, getGap1Size(image), 1, BMPFile); image->pixelData = malloc(sizeof(char) * getPixelDataSize(image)); fread(image->pixelData, sizeof(char) * getPixelDataSize(image), 1, BMPFile); fclose(BMPFile); return image; } void writeBMP(BMP* image, char* filepath) { FILE* BMPFile = fopen(filepath, "wb"); if (BMPFile == NULL) return; fwrite(image->bmpFileHeader, sizeof(BITMAPFILEHEADER), 1, BMPFile); fwrite(image->bmpInfo, sizeof(BITMAPINFO), 1, BMPFile); fwrite(image->gap1, getGap1Size(image), 1, BMPFile); fwrite(image->pixelData, sizeof(char), getPixelDataSize(image), BMPFile); fclose(BMPFile); } char** getPixelData(BMP* image) { char** pixelData = malloc(image->bmpInfo->biHeight * sizeof(char*)); for (int i = image->bmpInfo->biHeight - 1; i >= 0; i--) { pixelData[i] = malloc(image->bmpInfo->biWidth * sizeof(char*)); for (int j = 0; j < image->bmpInfo->biWidth; j++) { pixelData[i][j] = image->pixelData[i * (image->bmpInfo->biWidth + getPadding(image)) + j]; } } return pixelData; } void setPixelData(BMP* image, char** pixelData) { for (int i = image->bmpInfo->biHeight - 1; i >= 0; i--) { for (int j = 0; j < image->bmpInfo->biWidth; j++) { image->pixelData[i * (image->bmpInfo->biWidth + getPadding(image)) + j] = pixelData[i][j]; } } }
C
#include<stdio.h> #include<stdlib.h> #include<argz.h> #include<string.h> #include<regex.h> #include"gen_cmd.h" /* Private functions prototypes */ static int match_command_parse(const struct commands_t*, const char*, int*, size_t, regmatch_t*); static void show_match(const char* cmd, size_t nmatch, regmatch_t* pmatch); static char* copy_match(const char* cmd, regmatch_t* pmatch); /* Parse an expression to check if matches any command available in a dictionary * and extracted subcommand if any available. * * Full Description * Parse expression to check if it matches any command available in a dicionary. * * Arguments * commands - pointer to commands dictionary. * It may be a null pointer, if it is not then the last pattern * must point to null. * cmd - null terminated string containing expression to parse, it may be * a null pointer. * tokens - array of null terminated strings, each one containning one token. * It may be a null pointer without side effects. * The last element is always set to null to make this a null termited array. * ntokens - number of elements available on "tokens" * * Return * key binding of matched command. */ int command_parse(const struct commands_t* commands, const char* cmd, char** tokens, size_t ntokens) { regmatch_t* pmatch = 0; size_t nmatch = 0; int key = null_key; size_t i; /* Allocate object to hold tokens */ if (ntokens) { pmatch = malloc((ntokens) * sizeof(regmatch_t)); if (pmatch) { nmatch = ntokens; } } /* Check if expression matches any command */ if (!match_command_parse(commands, cmd, &key, nmatch, pmatch)) { /* Copy tokens if possible, it is up to the user to free * the allocated strings */ if (tokens) { /* Copy each token */ for(i = 1; i < nmatch; i++) { tokens[i - 1] = copy_match(cmd, &pmatch[i]); } /* Last token must point to null to make this a null terminated array */ tokens[ntokens - 1] = 0; } } else { /* Make all tokens null */ if (tokens) { for(i = 0; i < ntokens; i++) { tokens[i] = 0; } } } /* Free regmatch objects */ if (pmatch) free(pmatch); /* Return matched command key */ return key; } /* Parse an expression to check if matches any command available in a dictionary * * Full Description * Parse expression to check if it matches any command available in a dicionary. * * Arguments * commands - pointer to commands dictionary. * It may be a null pointer, if it is not then the last pattern * must point to null. * cmd - null terminated string containing expression to parse, it may be * a null pointer. * key - pointer here to store key binding of matched command, it may be a * null pointer. * nmatch - number of entries available on pmatch. * pmatch - regex structure containg byte offset of matched command pattern * groups. * * Return * 0 if there was a match, any other value otherwise. */ static int match_command_parse(const struct commands_t* commands, const char* cmd, int* key, size_t nmatch, regmatch_t* pmatch) { int lkey = null_key; int match = 1; regex_t preg; /* Only try to parse an expression if there is a command dictionary * and an expression to parse. */ if(commands && cmd) { /* Try to match expression with any command on dictionary. * A pointer to a null pattern indicate there is no more commands * on commands dictionary. */ while(commands->pattern && match) { /* Check if expression matchs current dictionary entry */ if (!regcomp(&preg, commands->pattern, REG_EXTENDED)) { match = regexec(&preg, cmd, nmatch, pmatch, 0); } regfree(&preg); /* If there is a match, store dictionary entry */ if (!match) { lkey = commands->key; //show_match(cmd, nmatch, pmatch); } commands++; } } /* Store command key if possible */ if (key) { *key = lkey; } /* Return 0 if expression matched any command, any other value otherwise */ return match; } void show_commands(const struct commands_t* commands) { printf("Commands:\n"); while(commands->cmd) { printf(" %s - %s\n", commands->cmd, commands->help); commands++; } printf("\n"); } /* show match */ static void show_match(const char* cmd, size_t nmatch, regmatch_t* pmatch) { size_t i; int j; /* Only try to parse an expression if there is an expression and a match */ if(cmd && pmatch && nmatch > 0) { for(i = 0; i < nmatch; i++) { printf("match[%d]: \"", i); for(j = pmatch[i].rm_so; j < pmatch[i].rm_eo; j++) { printf("%c", cmd[j]); } printf("\"\n"); } } } /* copy matched token * * Arguments * cmd - expression containing tokens * pmatch - regmatch containg byte offset of token in cmd * * Return * A dynamic allocated null terminated string containg token. * It is up to the USER to FREE the returned string if any. * This function may return null if there is no token to copy */ static char* copy_match(const char* cmd, regmatch_t* pmatch) { char* str = 0; size_t len = 0; if (cmd && pmatch) { len = pmatch->rm_eo - pmatch->rm_so; } if (len) { str = malloc((len + 1) * sizeof(char)); } if (str) { strncpy(str, &cmd[pmatch->rm_so], len); str[len] = 0; } return str; }
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { string girilecek_metin; string key = (argv[1]); if (argc != 2) { printf("Usage: ./vigenere keyword\n"); return 1; } int donusturulmus[strlen(key)]; //BIRINCI DONGU BASLANGICI for (int i = 0; i < strlen(key); i++) { if (isalpha(key[i]) == 0) { printf("invalid keyword\n"); return 1; } donusturulmus[i] = (int) key[i]; if (donusturulmus[i] >= 65 && donusturulmus[i] <= 90) { donusturulmus[i] = donusturulmus[i] - 65; } else if (donusturulmus[i] >= 97 && donusturulmus[i] <= 122) { donusturulmus[i] = donusturulmus[i] - 97; } } girilecek_metin = get_string("plaintext: "); int eleman = 0; printf("ciphertext: "); // IKINCI DONGU BASLANGICI for (int a = 0; a < strlen(girilecek_metin); a++) { if (girilecek_metin[a] <= 64 || (girilecek_metin[a] >= 91 && girilecek_metin[a] <= 96) || (girilecek_metin[a] >= 123 && girilecek_metin[a] <= 127)) { printf("%c", girilecek_metin[a]); } else { int sifrelenmis = donusturulmus[eleman] + girilecek_metin[a]; if (sifrelenmis >= 123 && isupper(girilecek_metin[a]) == false) { sifrelenmis = (sifrelenmis % 123) + 97; } else if (sifrelenmis >= 91 && isupper(girilecek_metin[a])) { sifrelenmis = (sifrelenmis % 91) + 65; } eleman = eleman + 1; eleman = eleman % strlen(key); printf("%c", sifrelenmis); } } printf("\n"); }
C
/* inimgrSave.c */ #include "inimgr_types.h" int inimgrSave( InimgrUID uid, const char *path, const char *sig, InimgrVersion version ) { struct inimgr_entry *entry; struct inimgr_context ctx = { (struct inimgr_params *)uid, NULL, INIMGR_OP_SAVE, }; int ret = CG_ERROR_OK; //if( CG_IS_VALID_UID( ctx.params->ini ) ){ // ctx.params->ini = fiomgrOpen( path, FH_O_RDWR | FH_O_CREAT | FH_O_ALLOC_HIGH, 0777 ); // if( ! CG_IS_VALID_UID( ctx.params->ini ) ) return ctx.params->ini; //} else{ // fiomgrSeek( ctx.params->ini, 0, FH_SEEK_SET ); //} /* t@C쐬A폜邽߂ɕKxJB ftruncate()قccB */ if( CG_IS_VALID_UID( ctx.params->ini ) ) fiomgrClose( ctx.params->ini ); ctx.params->ini = fiomgrOpen( path, FH_O_RDWR | FH_O_CREAT | FH_O_TRUNC | FH_O_ALLOC_HIGH, 0777 ); if( ! CG_IS_VALID_UID( ctx.params->ini ) ) return ctx.params->ini; if( sig && *sig != '\0' ){ fiomgrWrite( ctx.params->ini, (void *)sig, strlen( sig ) ); if( version ){ char ver_text[13]; unsigned char len; len = snprintf( ver_text, sizeof( ver_text ), " %d.%d.%d", (unsigned char)( version >> 16 ), (unsigned char)( version >> 8 ), (unsigned char)version ); fiomgrWriteln( ctx.params->ini, ver_text, len ); } } for( ctx.section = ctx.params->section; ctx.section; ctx.section = ctx.section->next ){ if( ! ctx.section->callback ) ctx.section->callback = __inimgr_find_callback( ctx.params, ctx.section->name ); /* ZNV̕INIMGR_DEFAULT_SECTIONwĂȂ΃ZNVL^ */ if( (void *)ctx.section->name != (void *)INIMGR_DEFAULT_SECTION ){ if( fiomgrTell( ctx.params->ini ) != 0 ) fiomgrWriteln( ctx.params->ini, "", 0 ); fiomgrWritefln( ctx.params->ini, ctx.params->buffer, sizeof( ctx.params->buffer ), "[%s]", ctx.section->name ); } if( ctx.section->callback ){ ret = ( ctx.section->callback->func )( (InimgrContext)&ctx, ctx.section->callback->arg ); if( ret != CG_ERROR_OK ) break; } else{ for( entry = ctx.section->entry; entry; entry = entry->next ){ inimgrWriteEntry( (InimgrContext)&ctx, entry->key, entry->value ); } } } // fiomgrTruncate( ctx.params->ini, fiomgrTell( ctx.params->ini ) ); return ret; }
C
// User-defined function line v2 #include <stdio.h> void line(int length, char ch) { int i; for(i = 1; i <= length; i ++) putch(ch); } void main() { starline(25); printf("\nSrikanth Technologies\n"); line(10,'-'); printf("\nWhere Quality Matters\n"); line(50,'='); } void starline(int length) { int i; for(i = 1; i <= length; i ++) putch('*'); }
C
/* * Student name: Minh Ha, UCSD student ID U07470714 * Email address: hahongminh@gmail.com * Course: C/C++ Programming I, Section ID 118011, instructor: Raymond Mitchell. * Date: 11/07/2016. * Name of this file: C1A6E1_main.c * Operating system: Windows 7. * Compiler & version: Visual C++ 2010. * * This program print the results of the standard strlen and of another function that * does the same thing. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> // Set up string buffer length #define LENGTH 129 // Function prototype for MyStrlen size_t MyStrlen(const char *s1); int main(void) { char inputString[LENGTH]; size_t length; // Getting user input and overwrite newline character with null terminator printf("Enter a string: "); fgets(inputString, LENGTH, stdin); length = strlen(inputString); if (length != 0 && inputString[length - 1] == '\n') inputString[--length] = '\0'; // Print the results printf("strlen(\"%s\") returned %u\n", inputString, (unsigned int)length); printf("MyStrlen(\"%s\") returned %u\n", inputString, (unsigned int)MyStrlen(inputString)); return(EXIT_SUCCESS); }
C
#include "gs.h" #include "sistLinear.h" #include <math.h> #include <stdio.h> //RETIRAR DEPOIS #include <sys/time.h> // Retorna tempo em milisegundos double timestamp(void) { struct timeval tp; gettimeofday(&tp, NULL); return((double)(tp.tv_sec*1000.0 + tp.tv_usec/1000.0)); } double normaAprox(double *Xold, double *Xnew, int MAX) { double r = 0; for (int i = 0; i < MAX; ++i) { r += (Xnew[i] - Xold[i])*(Xnew[i] - Xold[i]); } return sqrt(r); } double normaL2(double *Xnew, struct matPent *A, int MAX, int afast) { double r = 0; double aux; //PRIMEIRA ATRIBUICAO aux = (A->B[0] - (A->Dp[0]*Xnew[0] + A->Ds[0]*Xnew[1] + A->Dsa[0]*Xnew[afast + 2])); r += aux*aux; //r = (B[0] - A[0][-]*X)^2 //LOOP EM QUE DIAGONAL INFERIOR AFASTADA AINDA NAO APARECEU for(int i = 1; i < afast + 2; i++){ aux = (A->B[i] - (A->Dp[i]*Xnew[i] + A->Di[i]*Xnew[i - 1] + A->Ds[i]*Xnew[i + 1] + A->Dsa[i]*Xnew[afast + 2 + i])); r += aux*aux; } //LOOP EM QUE AMBAS DIAGONAIS AFASTADAS ESTAO PRESENTES for(int i = afast + 2; i < MAX - afast - 2; i++){ aux = (A->B[i] - (A->Dp[i]*Xnew[i] + A->Dia[i]*Xnew[i - afast - 2] + A->Di[i]*Xnew[i - 1] + A->Ds[i]*Xnew[i + 1] + A->Dsa[i]*Xnew[afast + 2 + i])); r += aux*aux; } //LOOP EM QUE DIAGONAL SUPERIROR AFASTADA ACABOU for(int i = MAX - afast - 2; i < MAX - 1; i++){ aux = (A->B[i] - (A->Dp[i]*Xnew[i] + A->Dia[i]*Xnew[i - afast - 2] + A->Di[i]*Xnew[i - 1] + A->Ds[i]*Xnew[i + 1])); r += aux*aux; } //ULTIMA ATRIBUICAO aux = (A->B[MAX - 1] - (A->Dp[MAX - 1]*Xnew[MAX - 1] + A->Dia[MAX - 1]*Xnew[MAX - afast - 3] + A->Di[MAX - 1]*Xnew[MAX - 2])); r += aux*aux; return sqrt(r);// retorna raiz de (r[0]^2+r[1]^2+...+r[n]^2) } //FUNCAO QUE CALCULA O VETOR RESULTADO DA ESTRUTURA ATRAVES DO METODO DE //GAUSS-SEIDEL, ELIMINANDO DO CALCULO AS OCORRENCIAS DE ZEROS void Gs(struct matPent *m, int afast, int MAX, int ite){ double Xold[MAX], Taux; unsigned int j = 0; for(int i = 0; i < MAX; i++) Xold[i] = 0; while(j < ite){ Taux = timestamp(); //PRIMEIRA ATRIBUICAO m->X[0] = m->B[0]/m->Dp[0] - m->Ds[0]*Xold[1]/m->Dp[0] - m->Dsa[0]*Xold[afast + 2]/m->Dp[0]; //LOOP EM QUE DIAGONAL INFERIOR AFASTADA AINDA NAO APARECEU for(int i = 1; i < afast + 2; i++) m->X[i] = m->B[i]/m->Dp[i] - m->Di[i]*m->X[i - 1]/m->Dp[i] - m->Ds[i]*Xold[i + 1]/m->Dp[i] - m->Dsa[i]*Xold[afast + 2 + i]/m->Dp[i]; //LOOP EM QUE AMBAS DIAGONAIS AFASTADAS ESTAO PRESENTES for(int i = afast + 2; i < MAX - afast - 2; i++) m->X[i] = m->B[i]/m->Dp[i] - m->Dia[i]*m->X[i - afast - 2]/m->Dp[i] - m->Di[i]*m->X[i - 1]/m->Dp[i] - m->Ds[i]*Xold[i + 1]/m->Dp[i] - m->Dsa[i]*Xold[afast + 2 + i]/m->Dp[i]; //LOOP EM QUE DIAGONAL SUPERIROR AFASTADA ACABOU for(int i = MAX - afast - 2; i < MAX - 1; i++) m->X[i] = m->B[i]/m->Dp[i] - m->Dia[i]*m->X[i - afast - 2]/m->Dp[i] - m->Di[i]*m->X[i - 1]/m->Dp[i] - m->Ds[i]*Xold[i + 1]/m->Dp[i]; //ULTIMA ATRIBUICAO m->X[MAX - 1] = m->B[MAX - 1]/m->Dp[MAX - 1] - m->Dia[MAX - 1]*m->X[MAX - afast - 3]/m->Dp[MAX - 1] - m->Di[MAX - 1]*m->X[MAX - 2]/m->Dp[MAX - 1]; m->T =+ (timestamp() - Taux)/ite; //tempo/maxIte m->r[j] = normaL2(m->X, m, MAX, afast); //m->r[j] = normaAprox(Xold, m->X, MAX); //X(ANTERIOR) = X(ATUAL) for(int i = 0; i < MAX; i++) Xold[i] = m->X[i]; j++; } }
C
// Used sample codes from October 12th discussion section. // Lawrence Lim // Perm: 4560892 /* Creates a datagram server. The port number is passed as an argument. This server runs forever */ #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> void error(const char *msg) { perror(msg); exit(0); } // Recursively add together the digits and send to client void recurse_addition (int sock, struct sockaddr_in from, socklen_t fromlen, char buffer [], int buffer_length) { if (buffer_length == 1) { int n = sendto(sock,buffer, 1, 0,(struct sockaddr *)&from,fromlen); if (n < 0) error ("sendto"); } else { int total = 0; for (int i = 0; i < buffer_length; i++) { total+= buffer[i] -48; } char new_buffer [128]; sprintf (new_buffer, "%d", total); int count = 0; while (new_buffer[count] != '\0' && count < 128) { count ++; } //write (1, new_buffer, count);i if (count > 1) { int n = sendto (sock, new_buffer, count, 0, (struct sockaddr *)&from,fromlen); if (n < 0) error ("sendto"); } recurse_addition (sock, from, fromlen, new_buffer, count); } } int main(int argc, char *argv[]) { int sock, length, n; socklen_t fromlen; struct sockaddr_in server; struct sockaddr_in from; char buf[1024]; if (argc < 2) { fprintf(stderr, "ERROR, no port provided\n"); exit(0); } 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(atoi(argv[1])); if (bind(sock,(struct sockaddr *)&server,length)<0) error("binding"); fromlen = sizeof(struct sockaddr_in); while (1) { n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen); if (n < 0) error("recvfrom"); // First check there are no non-numerical characters int count = n; int non_num = 0; int ignore_last = 0; for (int i = 0; i < count; i++) { if (i != count-1 && (buf [i] < '0' || buf [i] > '9')) non_num = 1; else if (i == count-1) { if (buf [i] < '0' || buf [i] > '9') ignore_last = 1; } } if (non_num) { n = sendto(sock,"Can not compute",17, 0,(struct sockaddr *)&from,fromlen); } else { char newstr [1024]; strcpy(newstr, buf); if (ignore_last) { count = count-1; newstr [count] = '\0'; } recurse_addition (sock, from, fromlen, newstr, count); } if (n < 0) error("sendto"); } return 0; }
C
#include<stdio.h> #include<stdlib.h> int main (void) { float n1, quadrado; printf ("Digite um numero: \n"); scanf ("%f", &n1); quadrado= n1*n1; printf ("O resultado do quadrado do numero eh = %.f\n", quadrado); system ("pause"); return (0); }
C
/* * file main.c * brief programme d'analyse des mcanismes de gestion de la pile * author */ /* * program entry point */ int main(void){ /* pushl %ebp : sauvegarde le contexte de la fonction appelante movl %esp, %ebp : prparation l'allocation de ressources mmoire pour le contexte de la fonction courante ou fonction main ---> contenu de la pile reprsent ci-contre aprs excution de cette instruction */ return 0; /* movl $0, %eax : passage par registre de la valeur de retour popl %ebp : restaure le contexte de la fonction appelante ret : dpile l'adresse de retour de la fonction appelante et la charge dans le pointeur d'instruction puis quitte la fonction main */ }
C
#include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char** argv){ char *path; DIR* dp; struct dirent* dentry; struct stat buf; char *ptr; if(argc==1) path = "."; else if(argc==2){ path = argv[1]; chdir(argv[1]);} else{ printf("usage: my_ls dirname\n"); exit(1); } if(!(dp=opendir(path))){ printf("opendir error.\n"); exit(2); } while(1){ dentry = readdir(dp); if(!dentry) break; if(!strcmp(dentry->d_name,".") || !strcmp(dentry->d_name, "..")) continue; if(lstat(dentry->d_name, &buf) < 0){ perror("lstat()"); continue; } if(S_ISDIR(buf.st_mode)) printf("d"); else if(S_ISREG(buf.st_mode)) printf("-"); else if(S_ISLNK(buf.st_mode)) printf("l"); if(S_IRUSR & buf.st_mode) printf("r"); else printf("-"); if(S_IWUSR & buf.st_mode) printf("w"); else printf("-"); if(S_IXUSR & buf.st_mode) printf("x"); else printf("-"); if(S_IRGRP & buf.st_mode) printf("r"); else printf("-"); if(S_IWGRP & buf.st_mode) printf("w"); else printf("-"); if(S_IXGRP & buf.st_mode) printf("x"); else printf("-"); if(S_IROTH & buf.st_mode) printf("r"); else printf("-"); if(S_IWOTH & buf.st_mode) printf("w"); else printf("-"); if(S_IXOTH & buf.st_mode) printf("x"); else printf("-"); printf(" %10lu %s\n", buf.st_size, dentry->d_name); } closedir(dp); 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 pid_t ; /* Variables and functions */ int /*<<< orphan*/ O_WRONLY ; int /*<<< orphan*/ WNOHANG ; int /*<<< orphan*/ W_OK ; scalar_t__ access (char*,int /*<<< orphan*/ ) ; int atoi (char*) ; scalar_t__ chdir (char*) ; int /*<<< orphan*/ chmod (char*,int) ; int /*<<< orphan*/ close (int) ; int con_sock ; scalar_t__ daemonize ; int /*<<< orphan*/ exit (int) ; char* fetch_mode ; int fork () ; char* getenv (char*) ; scalar_t__ geteuid () ; int getopt (int,char**,char*) ; char* homedir ; int http_port ; int /*<<< orphan*/ http_request () ; int /*<<< orphan*/ http_sock ; int /*<<< orphan*/ init_servconnection () ; scalar_t__ listen (int /*<<< orphan*/ ,int) ; char* logfile ; int open (char*,int /*<<< orphan*/ ) ; char* optarg ; int /*<<< orphan*/ perror (char*) ; int /*<<< orphan*/ printf (char*,...) ; int /*<<< orphan*/ puts (char*) ; int /*<<< orphan*/ setpgrp (int,int) ; int /*<<< orphan*/ strcat (char*,char*) ; int /*<<< orphan*/ strcpy (char*,char*) ; int verbose ; int /*<<< orphan*/ wait3 (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ wait_connection () ; int main(int argc, char *argv[]) { int ch, ld; pid_t httpd_group = 65534; pid_t server_pid; /* Default for html directory */ strcpy (homedir,getenv("HOME")); if (!geteuid()) strcpy (homedir,"/httphome"); else strcat (homedir,"/httphome"); /* Defaults for log file */ if (geteuid()) { strcpy(logfile,getenv("HOME")); strcat(logfile,"/"); strcat(logfile,"jhttp.log"); } else strcpy(logfile,"/var/log/jhttpd.log"); /* Parse command line arguments */ while ((ch = getopt(argc, argv, "d:f:g:l:p:vDh")) != -1) switch (ch) { case 'd': strcpy(homedir,optarg); break; case 'f': daemonize = 0; verbose = 1; fetch_mode = optarg; break; case 'g': httpd_group = atoi(optarg); break; case 'l': strcpy(logfile,optarg); break; case 'p': http_port = atoi(optarg); break; case 'v': verbose = 1; break; case 'D': daemonize = 0; break; case '?': case 'h': default: printf("usage: simple_httpd [[-d directory][-g grpid][-l logfile][-p port][-vD]]\n"); exit(1); /* NOTREACHED */ } /* Not running as root and no port supplied, assume 1080 */ if ((http_port == 80) && geteuid()) { http_port = 1080; } /* Do we really have rights in the html directory? */ if (fetch_mode == NULL) { if (chdir(homedir)) { perror("chdir"); puts(homedir); exit(1); } } /* Create log file if it doesn't exit */ if ((access(logfile,W_OK)) && daemonize) { ld = open (logfile,O_WRONLY); chmod (logfile,00600); close(ld); } init_servconnection(); if (verbose) { printf("Server started with options \n"); printf("port: %d\n",http_port); if (fetch_mode == NULL) printf("html home: %s\n",homedir); if (daemonize) printf("logfile: %s\n",logfile); } /* httpd is spawned */ if (daemonize) { if ((server_pid = fork()) != 0) { wait3(0,WNOHANG,0); if (verbose) printf("pid: %d\n",server_pid); exit(0); } wait3(0,WNOHANG,0); } if (fetch_mode == NULL) setpgrp((pid_t)0, httpd_group); /* How many connections do you want? * Keep this lower than the available number of processes */ if (listen(http_sock,15) < 0) exit(1); label: wait_connection(); if (fork()) { wait3(0,WNOHANG,0); close(con_sock); goto label; } http_request(); wait3(0,WNOHANG,0); exit(0); }
C
#include<stdio.h> int main() { char str[100],rev[100]; int i=0,len=0,pal=0; scanf("%s",str); while(str[i]!='\0') { len++; i++; } i=0; if(str[i]!=str[len-1]) printf("-1"); else { while(str[i]!='\0') { if(str[i]=='.') { if(str[i+1]!='a') str[i]=str[i+1]-1; else str[i]=str[i+1]; }//if i++; }//while i=0; while (len>0) { rev[i]=str[len-1]; i++; len--; }//while rev[i]='\0'; i=0; while(str[i]!='\0') { if(str[i]!=rev[i]) { pal=1; break; } i++; }//while if(pal==0) printf("%s",str); else printf("-1"); } return 0; }
C
/* ** left_key.c for 42sh in /home/hurlu/PSU_2015_42sh/src/line_edit ** ** Made by Hugo Willaume ** Login <willau_h@epitech.net> ** ** Started on Sat Jun 4 14:16:54 2016 Hugo Willaume ** Last update Sun Jun 5 23:05:57 2016 Hugo Willaume */ #include <curses.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include "misc.h" #include "line_edit.h" static void prev_line(int *idx, char **result, t_tty *term) { (void)idx; (void)result; write(1, tigetstr("cuu1"), strlen(tigetstr("cuu1"))); while (term->cur_pos.x < term->width - 1) { term->cur_pos.x++; write(1, tigetstr("cuf1"), strlen(tigetstr("cuf1"))); } term->cur_pos.y--; } int go_left(char **result, int *idx, char *escape_seq, t_tty *term) { if (strcmp(escape_seq, term->capacities[0]) != 0 && escape_seq[0] != 2) return (1); if ((*idx) > 0) { if (term->cur_pos.x == 0) prev_line(idx, result, term); else { term->cur_pos.x--; write(1, "\b", 1); } (*idx)--; } return (0); }
C
#include "multitask.h" #include "memory.h" #include "vga.h" #include "interrupt.h" #define STACK_SIZE 2*1024*1024 struct Process *curr_proc, *next_proc; struct Process dummy_process = { .nextProc=&dummy_process, .prevProc=&dummy_process }; struct Process *all_procs = &dummy_process; struct ProcessQueue readyQueue = {.head=0}; void runSchedule() { if(curr_proc->currQueue == &readyQueue){ next_proc = curr_proc->nextInQueue; } else if(readyQueue.head != 0){ next_proc = readyQueue.head; } else{ next_proc = &dummy_process; } } void unlinkFromQueue(struct Process *proc) { if(proc->nextInQueue == proc){ proc->currQueue->head = 0; } else{ proc->nextInQueue->prevInQueue = proc->prevInQueue; proc->prevInQueue->nextInQueue = proc->nextInQueue; if(proc->currQueue->head == proc){ proc->currQueue->head = proc->nextInQueue; } } proc->currQueue = 0; } void appendToQueue(struct Process *newProc, struct ProcessQueue *queue) { newProc->currQueue = queue; if(queue->head == 0){ newProc->nextInQueue = newProc; newProc->prevInQueue = newProc; queue->head = newProc; } else{ newProc->prevInQueue = queue->head->prevInQueue; queue->head->prevInQueue->nextInQueue = newProc; queue->head->prevInQueue = newProc; newProc->nextInQueue = queue->head; } } void PROC_run() { curr_proc = &dummy_process; yield(); } struct Process * PROC_create_kthread(kproc_t entry_point, void* arg) { static int pid=1; struct Process *newProc = (struct Process *)kmalloc(sizeof(struct Process)); newProc->pid = pid++; //setup stack newProc->stack_start = kmalloc(STACK_SIZE); newProc->rsp = (uint64_t)newProc->stack_start + STACK_SIZE - 16; *((uint64_t*)(newProc->rsp)) = (uint64_t)kexit; //return address on stack //setup other registers newProc->rip = (uint64_t)entry_point; asm ("mov %%cs, %0":"=r"(newProc->cs)); asm ("pushf; mov (%%rsp), %0; popf":"=r"(newProc->rflags)); asm ("mov %%ss, %0":"=r"(newProc->ss)); newProc->rdi = (uint64_t)arg; //add into process circular list newProc->prevProc = all_procs->prevProc; all_procs->prevProc->nextProc = newProc; all_procs->prevProc = newProc; newProc->nextProc = all_procs; //add to ready queue appendToQueue(newProc, &readyQueue); return newProc; } void PROC_reschedule() { runSchedule(); } //system call 1 void yieldSysCall() { runSchedule(); } //system call 2 void kexitSysCall(void) { struct Process *removed = curr_proc; removed->nextProc->prevProc = removed->prevProc; removed->prevProc->nextProc = removed->nextProc; unlinkFromQueue(removed); runSchedule(); kfree(removed->stack_start); kfree(removed); curr_proc = (struct Process *)0; } void sysCallISR(int call_number, void * arg1, void* arg2, void* arg3, void* arg4, void* arg5) { switch (call_number) { case 1: yieldSysCall(); break; case 2: kexitSysCall(); break; default: break; } } void PROC_block_on(struct ProcessQueue *queue, int enable_ints) { if(!queue){ return; } unlinkFromQueue(curr_proc); appendToQueue(curr_proc, queue); if(enable_ints){ STI; } yield(); } void PROC_unblock_head(struct ProcessQueue *queue) { struct Process *proc = queue->head; unlinkFromQueue(proc); appendToQueue(proc, &readyQueue); } void PROC_unblock_all(struct ProcessQueue *queue) { while(queue->head){ PROC_unblock_head(queue); } } void PROC_init_queue(struct ProcessQueue *queue) { queue->head = 0; }
C
#include <stdlib.h> #include <stdio.h> #include "node.c" #define INF 2147483647 //Maior valor que um inteiro pode assumir. int main() { int count = 0; int total = 0; int largest = -1*(INF-1); int i; Node *nodes = NULL; while( (scanf("%d",&i) == 1 )) { nodes = makeNode(i, nodes); if( i > largest) largest = i; } printf( "Valor máximo: %d\n", largest); while( nodes != NULL ) { i = getValue(nodes); if( largest % i == 0 ) { total += i; count++; } nodes = getNext(nodes); } if(count != 0) printf( "Média: %d\n", (total/count)); }
C
// Copyright 2017.|| // author|| // ָ #include <stdio.h> void func(float** p); void func1(float** p); void func2(float** p); int main(int argc, char* argv[]) { int i; int j; float* p[3]; float score[3][4] = {{65, 67, 70, 60}, {80, 87, 90, 81}, {90, 99, 100, 98}}; for (i = 0; i != 3; ++i) { p[i] = score[i]; } func(p); func1(p); // func2(p); printf("%4.2f\n", score[0][0]); printf("\n"); printf("%4.2f\n", p[1][0]); printf("%4.2f\n", p[0][0]); // func1,p[0]ΪNULL return 0; } void func(float** p) { **p = 102; } void func1(float** p) { *p = NULL; } void func2(float** p) { p = NULL; }
C
#include <stdio.h> int main(void){ int a=10; int *p; /*int *p=(int *)0xDEADBEEF;//PASSING AN ADDRESS MANUALLY TO THE POINTER*/ printf("adress1 of p is : %p\n",p); /*printf("value of a is : %i\n",*p);// will fail since we try to acess that mem which we are not supposed to access*/ p=&a; printf("adress2 of p is : %p\n",p); printf("value of a is : %i\n",*p); char *s="hello world"; char d; s=&d; /*p=&a;*/ printf("adress of a is : %p\n",&a); printf("value of a is : %i\n",a); printf("adress of a is : %p\n",s); printf("value of a is : %c\n",*s); for (int i=0;*(s+i)!= '\0';i++){ printf("address of %c is : %p\n",*(s+i),s+i); } printf("\n"); printf("word is : %s\n",s); int x[100]; x[0]=112; printf("content of x is : %i\n",*x);// content of address pointed by the first address in array printf("address of x is : %p\n",x+1);//adress is incremented by 4 bytes ,since int requires 4 bytes printf("address of x is : %p\n",x+2); }
C
#include <stdio.h> #include <stdlib.h> #define NELEMS(a) ((int)(sizeof(a) / sizeof(a[0]))) #define DUMP(n) printf(#n " has %d elements\n", NELEMS(n)) int main(void) { int i[42], *p = i; DUMP(i); DUMP(p); return 0; }
C
/* * SIGNALS * HUP - SIGHUP - handing the process * INT - SIGINT (ctrl-c) - interruption the process * TERM - SIGTERM - finish * USR1, USR2 * * int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); * */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> // sleep #include <signal.h> // ctrl+z #include <string.h> #include <time.h> // for time(NULL) #include "part3.h" time_t start_time; struct server_info info ; void sighandler(int sign_num){ switch (sign_num){ case SIGINT: { // ctrl - c printf("\tsigint: Process ID: %d\n",info.process_ID); break; } case SIGHUP:{ printf("\tsighup: %d seconds after start\n",(int)info.current_time); break; } case SIGTERM:{ printf("\tsigterm: Average system load [1/5/15 minutes]: %.4f, %.4f, %.4f\n", info.loadavg[0],info.loadavg[1], info.loadavg[2]); break; } case SIGUSR1:{ // kill(pid, SIGUSR1); printf("\tsigusr1: Process user ID: %d\n",info.process_user_ID); break; } case SIGUSR2: { // ==||==||== printf("\tsigusr2: Process group ID: %d\n",info.process_user_ID); break; } case SIGTSTP:{ printf("\tGood bye :(\n"); exit(EXIT_SUCCESS); } } } struct server_info save_info(){ struct server_info info; info.process_ID = getpid(); info.process_user_ID = getuid(); info.process_group_ID = getgid(); info.current_time = difftime(time(NULL),start_time); getloadavg(info.loadavg,3); return info ; } int main(int argc, char *agrv[]){ start_time = time(NULL); info = save_info(); printf("Signals: [kill -n pid]" "\n\tint #2 process ID (ctrl-c)" "\n\thup #1 current time" "\n\tterm #15 loadavg" "\n\tusr1 #10 process user ID" "\n\tusr2 #12 process group ID" "\n\ttstp #20 exit (ctrl-z)\n"); signal(SIGINT, sighandler); signal(SIGHUP,sighandler); signal(SIGTERM,sighandler); signal(SIGUSR1,sighandler); signal(SIGUSR2,sighandler); signal(SIGTSTP,sighandler); while(1){ info.current_time = difftime(time(NULL), start_time); getloadavg(info.loadavg, 3); sleep(1); } return 0; }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* get_next_line.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: cgarrot <marvin@le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/10/11 22:19:50 by cgarrot #+# ## ## #+# */ /* Updated: 2018/11/09 21:22:28 by cgarrot ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "get_next_line.h" #include <stdio.h> int past_line(char **str, char **line, const int fd) { int i; i = 0; if (str[fd][i]) { if (ft_strchr(str[fd], '\n')) { while (str[fd][i] != '\n' && str[fd][i]) i++; if (!(*line = ft_strsub(str[fd], 0, i))) return (-1); str[fd] = &str[fd][i + 1]; return (1); } if (!(*line = ft_strdup(str[fd]))) return (-1); str[fd][0] = '\0'; } return (-1); } int get_next_line(const int fd, char **line) { int ret; char buff[BUFF_SIZE + 1]; static char *str[10240]; char *tmp; if (fd < 0 || !line || read(fd, buff, 0) < 0 || BUFF_SIZE <= 0) return (-1); if (!str[fd]) str[fd] = ft_strnew(0); while ((ret = read(fd, buff, BUFF_SIZE))) { buff[ret] = '\0'; tmp = str[fd]; if (!(str[fd] = ft_strjoin(tmp, buff))) return (-1); if (ft_strlen(tmp)) free(tmp); if (ret < 0) return (-1); } if (str[fd][0] == '\0') return (0); past_line(str, line, fd); return (1); } int main(int argc, char **argv) { int fd; char*line; if (argc == 1) fd = 0; else if (argc == 2) fd = open(argv[1], O_RDONLY); else return (2); while (get_next_line(fd, &line) == 1) { ft_putendl(line); free(line); } if (argc == 2) close(fd); }
C
#include <stdio.h> enum operaciones { SUMAR = 1, RESTAR, DIVIDIR, MULTIPLICAR }; void menu(); int main(int argc, char const *argv[]) { enum operaciones operacion; float operador1, operador2; do { menu(); printf("Seleccione una operación 1-4: "); scanf("%d", &operacion); if (operacion == 5) { break; } printf("Ingrese el primer operador: "); scanf("%f", &operador1); printf("Ingrese el segundo operador: "); scanf("%f", &operador2); switch (operacion) { case SUMAR: printf("%f + %f = %f\n", operador1, operador2, operador1 + operador2); break; case RESTAR: printf("%f - %f = %f\n", operador1, operador2, operador1 - operador2); break; case DIVIDIR: printf("%f / %f = %f\n", operador1, operador2, operador1 / operador2); break; case MULTIPLICAR: printf("%f * %f = %f\n", operador1, operador2, operador1 * operador2); break; } } while (operacion != 5); return 0; } void menu() { printf("\n1.Sumar\n2.Restar\n3.Mutilplicar\n4.Dividir\n5.Salir\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { FILE *pfile; char cDate[5], cTel[20], cBuf[80]; if((pfile=fopen("message.txt","r+"))==NULL) { printf("message.txt ɮ׵Lk}"); system("pause"); return(0); } //}ҧsɮ while( !feof(pfile) ) { // ɮתe fgets(cBuf,80,pfile); printf("%s",cBuf); } rewind(pfile); //ŪgY^ɮY printf("\nJf:"); gets(cDate); if( strlen(cDate) == 1 ) { //u@Ӧr cDate[2] = '\0'; cDate[1] = cDate[0]; cDate[0] = ' '; // eɤ@Ӫť } printf("Jsq:"); gets(cTel); // NŪgYVm,OBytes fseek(pfile,20,SEEK_SET); fputs(cDate,pfile); // NŪgYVqܪm fseek(pfile,48,SEEK_SET); fputs(cTel,pfile); rewind(pfile); //ŪgY^ɮY while( !feof(pfile) ) { // ɮתe fgets(cBuf,80,pfile); printf("%s",cBuf); } fclose(pfile); system("pause"); return(0); // ɮ }
C
#include<p24Fxxxx.h> #include"i2c.h" #include"delay.h" #define STA311B_ADDR_WR 0x40 #define STA311B_ADDR_RD 0x41 void I2C_Init() { //I2C1CONbits.I2CEN=1;// //I2C1BRG=0x4f;//100KHZ I2C3CONbits.I2CEN = 1; I2C3CONbits.ACKEN = 1; I2C3BRG = 0x9D;//100KHZ Fcy=16Mhz } void I2C_Start() { I2C3CONbits.SEN=1; while(I2C3CONbits.SEN); //Wait till Start sequence is completed IFS5bits.MI2C3IF=0; } void I2C_RStart() { I2C3CONbits.RSEN=1; while(I2C3CONbits.RSEN); //Wait till Start sequence is completed IFS5bits.MI2C3IF=0; } void I2C_Stop() { I2C3CONbits.PEN=1; //ֹͣI2CߣӲԶ while(I2C3CONbits.PEN); //Wait till Stop sequence is completed IFS5bits.MI2C3IF=0; } void I2C_WriteByte(unsigned char dat) { I2C3TRN=dat; while(I2C3STATbits.TBF);//Wait for send complete while(!IFS5bits.MI2C3IF); //Wait for ninth clock cycle IFS5bits.MI2C3IF=0; //Clear interrupt flag } unsigned char I2C_ReadByte() { unsigned char temp; I2C3CONbits.RCEN=1; while(!I2C3STATbits.RBF);//ɣ־λ temp=I2C3RCV;//ȡյ return temp; } void I2C_Read_Ack() { while(I2C3STATbits.ACKSTAT);// ȴӦӦ1 } void I2C_Send_Ack() { I2C3CONbits.ACKDT=1; I2C3CONbits.ACKEN=1; } void I2C_Start_Wait(uint8_t addr) { I2C_Start(); I2C_WriteByte(addr); } void I2C_WriteChar(unsigned int addr,unsigned char dat) { I2C_Start(); I2C_WriteByte(STA311B_ADDR_WR); I2C_Read_Ack(); I2C_WriteByte(addr); I2C_Read_Ack(); I2C_WriteByte(dat); I2C_Read_Ack(); I2C_Stop(); } void I2C_WriteString(unsigned int addr,unsigned char *dat) { while(*dat!='\0') { I2C_WriteChar(addr,*dat); addr++; dat++; delay_ms(30); } } unsigned char I2C_ReadChar(unsigned int addr) { unsigned char temp; I2C_Start(); I2C_WriteByte(STA311B_ADDR_WR); I2C_Read_Ack(); I2C_WriteByte(addr); I2C_Read_Ack(); I2C_RStart(); // I2C_WriteByte(STA311B_ADDR_RD); I2C_Read_Ack(); temp=I2C_ReadByte(); //I2C_Send_Ack(); I2C_Stop(); return temp; }
C
// // main.c // d1 // // Created by Slava Gubar on 01.02.2021. // #include <stdio.h> #include "math.h" //#include <string.h> //#include <memory.h> #include <stdlib.h> int main(int argc, const char * argv[]) { int y = 0; int a = 5; int *b = &a; int *k = NULL; if (k != NULL) { int bk = *k; } int c = *b; int d[9]; int size = sizeof(d); int count = sizeof(d)/sizeof(d[0]); int *array = d; int *g = array + 1; int z = *(array + 1); int z1 = *g; int z2 = g[1]; // == d[2] int z3 = d[1]; char ax = 'a'; char ax_str[] = "test"; char *ax_str2 = "test"; int *arr_int = (int *)malloc(sizeof(int) * 10); if (arr_int != NULL) { int zx = *(arr_int + 1); char *arr_char = (char *)arr_int; char zc = *(arr_char + 1); free(arr_int); arr_int = NULL; } int sizeOfArray = sizeof(array); // sizeof int *array int x2[5][6]; int **y2 = create_matrix(5, 6); int sum = matrix_sum(y2, 5, 6); if (sum == -1) { printf ("Fail\n"); } delete_matrix(y2, 5); y2 = NULL; a = 6; // insert code here... printf("Hello, World! len: %d\n", dk_strlen("test of len")); return 0; }
C
#include "variadic_functions.h" #include <stdio.h> /** * print_numbers - prints numbers, followed by a new line * @separator: pointer to char * @n: unsigned int * Return: 0 */ void print_numbers(const char *separator, const unsigned int n, ...) { va_list num; unsigned int i; va_start(num, n); for (i = 0; i < n; i++) { if (!separator || (separator && i == 0)) printf("%d", va_arg(num, int)); else printf("%s%d", separator, va_arg(num, int)); } printf("\n"); va_end(num); }
C
// Rattle Sort // // Altering Bubble Sort to be O(n log n) time complexity for the best, worst, and average cases. // // Author: Stew Forster (stew675@gmail.com) Date: 19th July 2021 // // Essentially a bi-directional comb-sort but with an algorithmically optimal step progression. // Comb-sort tops out at a 1.3x ratio, but rattle-sort achieves a 1.333x ratio, meaning that it // scales better for medium+ (>10K) n-values and is generally slightly faster in all scenarios // Faster than median-of-3 q-sort for n values up to 1600 when sorting integers/pointers. It // gets progressively slower than such qsort implementations for very large n-values but still // usually stays within a 1.0-1.25x time-to-run range of qsort even up to n=100M // // Extensive brute-force empirical analysis found that the 4/3 ratio was the natural cadence // of RattleSort's step progression // // The step-set implementation offers something of a twist to how step-sizes are generated. // Initially step-sizes are calculated as n/steps[pos] up until step exceeds sqrt(n), after // which point we reverse direction in the step-set and the step-dividers become the actual // step-sizes themselves. This guarantees no set-size degeneracy for pretty much any value // of n, and therefore the input is almost always near-fully sorted by the time a step-size // of 1 is reached, after which the algorithm acts as a 2-way bubble sort with collapsing // ends and quickly mops up any remaining positional stragglers // // As such the algorithm is O(N log₁.₃₃N) where the log base is 1.333 and the number of compares // is uniform for all step sizes >1. Technically, due to the final stage bubble-sort, the // algorithm could be claimed to be O(n^2) in the worst-case, but I have difficulty conceiving // how such a worst-case data set could be constructed given the sheer number of prime-based // steps involved. Values would need to remain near invariant with respect to ther locality // across a mind-boggingly large greatest-common-multiple set space to arrive at a poorly // sorted set by the time we reach the step=1 bubble-sort phase. I have yet to personally // witness anything other than O(n logn) behavior for n>100 with time-variancy mostly occuring // due to the number of swaps required. It is my running supposition that the number of // 1-step passes will never exceed ceil(log₁.₃₃N) or ceil(log(n)/log(4.0/3.0)) and to date // neither any brute force scenarios, nor have any random data sets ever violated this // supposition with the peak number of 1-step passes appearing to diminish for large values // for n // // Therefore, it is posited that the absolute worst case consists of log₁.₃₃N steps of step // sizes greater than 1, and up to log₁.₃₃N 1-step passes. Since each pass traverses, at // most, N elements (often much less), this creates a worst case of 2*N*log₁.₃₃N compares // and the number of swaps is, of course, capped by the number of compares. // // The results below demonstrate this effect. I brute-forced every permutation for array // sizes up to 14 (15 and 16 still calculating) and the worst-case number of swaps does not // follow an O(n^2) sequence. I experimentally hammered the algorithm with ~1 trillion // input sets for larger values of n, and found that the worst-case number of swaps actually // approaches the average case as n is raised. // // Worst Case Brute-Force results in terms of total SWAPS required to sort // MAX MAX nPERM AVG nWORST SAMPLE WORST CASE SET // N 1-PASS SWAPS SWAPS SETS // 16 6 61 16! 26.564 17 [15, 16, 6, 10, 2, 8, 13, 5, 14, 11, 4, 9, 1, 7, 12, 3] // 15 6 52 15! 23.511 57 [8, 15, 5, 12, 10, 4, 13, 7, 14, 2, 9, 6, 3, 11, 1] // 14 6 48 14! 20.605 1 [12, 14, 6, 2, 11, 8, 5, 10, 13, 4, 1, 9, 7, 3] // 13 7 43 13! 18.413 28 [4, 13, 5, 9, 7, 11, 3, 12, 2, 8, 6, 10, 1] // 12 7 41 12! 16.062 1 [12, 6, 8, 2, 10, 4, 11, 5, 7, 1, 9, 3] // 11 5 29 11! 13.298 6 [4, 11, 5, 8, 9, 3, 10, 2, 7, 6, 1] // 10 4 26 10! 11.195 2 [10, 4, 7, 8, 3, 9, 2, 6, 5, 1] // 9 3 19 9! 9.206 2 [8, 9, 2, 4, 7, 5, 1, 3, 6] // 8 5 20 8! 8.324 1 [8, 4, 6, 2, 7, 3, 5, 1] // 7 4 14 7! 7.433 9 [3, 7, 5, 2, 6, 4, 1] // 6 4 12 720 5.500 1 [6, 4, 2, 5, 3, 1] // 5 3 7 120 3.800 4 [3, 5, 2, 4, 1] // 4 3 5 24 2.333 1 [4, 2, 3, 1] // 3 3 3 6 1.500 1 [3, 2, 1] // 2 2 1 2 0.500 1 [2, 1] // 1 1 0 1 0.000 1 [1] // // Since the number of permutations is O(n!) then values for N above 16 become prohibitively // expensive to computationally brute-force to find the worst case set, I had to resort to // anecdotal/empirical result gathering, the results of which are presented below // // Worst Case for number of 1-step passes seen anecdotally with random data sets. Most runs // typically consist of 100M-10B randomly generated data sets of unique elements, which are // then sorted, and the maximum number of 1-step passes seen is then recorded // // MAX MAX AVG // N 1-PASS SWAPS SWAPS Notes // 9973 7 70419 68331 * 100M passes // 5000 8 32696 31344 * 100M passes // 2000 8 12215 11246 * 100M passes // 1000 8 5593 4965 * 100M passes // 500 9 2762 2171 * 1B passes // 200 9 1065 720 * 1B passes // 100 10 436 300 * 1B passes // 50 9 205 118 * 1B passes // 40 9 182 91 * 10B passes // 30 9 133 62.4 * 10B passes // 20 8 74 31.5 * 10B passes // 18 8 73 29.494 * 10B passes // 16 6 59 26.564 * 10B passes // 15 6 51 23.511 * 100B passes // 14 6 46 20.605 * Results closely match exhaustive brute force observation // 13 7 43 18.413 * Results perfectly match exhaustive brute force observation // 12 7 41 16.062 * Results perfectly match exhaustive brute force observation // 11 5 29 11.298 * Results perfectly match exhaustive brute force observation #include <stddef.h> #include <stdint.h> #include "swap.h" // 4/3 => 1.333333333333 // Best overall balanced performance. The 4294967295 value acts as a sentinel. This step set supports // n values up to 10^10. Higher n values will still work, the algorithm will just start to slow down. // The step set can be expanded with more values, but an n value of 10^10 should satisfy most things //static const size_t steps[] = {1, 2, 3, 5, 7, 11, 13, 17, 23, 31, 43, 59, 73, 101, 131, 179, 239, 317, 421, 563, 751, 997, 1327, 1777, // 2357, 3137, 4201, 5591, 7459, 9949, 13267, 17707, 23599, 31469, 41953, 55933, 74573, 99439, 4294967295}; static const size_t steps[] = {1, 2, 3, 5, 7, 11, 13, 17, 23, 31, 43, 59, 73, 101, 131, 179, 239, 317, 421, 563, 751, 997, 1327, 1777, 2357, 3137, 4201, 5591, 7459, 9949, 13267, 17707, 23599, 31469, 41953, 55933, 74573, 99439, 4294967295}; #define CUTOFF 20 void rattle_sort(register char *a, size_t n, register const size_t es, register const int (*is_lt)(const void *, const void *)) { register char *b, *c, *s, *e = a + n * es; register int swaptype; register WORD t; size_t step = n; int pos = 0; SWAPINIT(a, es); #define next_step ((step > steps[pos+1]) ? (n / steps[++pos]) : (pos > 0 ? steps[--pos] : 1)) while (step > CUTOFF) { for (step = next_step, b=a, c=a+(step*es); c<e; b+=es, c+=es) if (is_lt(c, b)) swap(b, c); for (step = next_step, b=e-es, c=b-(step*es); c>=a; b-=es, c-=es) if (is_lt(b, c)) swap(b, c); } #undef next_step // At this point everything should be <10 positions of where it needs to be, // and most typically within 0-2 positions. It so happens that insertion sort // is actually very efficient for sorting such really quickly, so we do that for (s=a, b=a+es; b<e; s=b, b+=es) for (c=b; c>a && is_lt(c, s); c=s, s-=es) swap(c, s); } // rattle_sort
C
#include <stdio.h> #include <string.h> main(){ int n, test,i,j, cont=0; char pomekon[1000][1000]; scanf("%d",&n); getchar(); for(i = 0; i < n; i++){ gets(pomekon[i]); test = 1; for(j = 0; j < i;j++){ if(strcmp(pomekon[j],pomekon[i]) == 0){ test = 0; break; } } if(test == 1)cont++; } printf("Falta(m) %d pomekon(s).\n", 151 - cont); }
C
#include "sys/mem_allocator.h" #include "sys/ref_count.h" #include "sys/sys.h" #include "window_manager/glfw/wm_glfw_device_c.h" #include "window_manager/wm.h" #include "window_manager/wm_device.h" #include "window_manager/wm_window.h" #include <GL/glfw.h> #include <assert.h> #include <limits.h> #include <stdlib.h> struct wm_window { struct ref ref; struct wm_device* device; bool fullscreen; }; /******************************************************************************* * * Helper functions. * ******************************************************************************/ static void release_window(struct ref* ref) { struct wm_device* dev = NULL; struct wm_window* win = NULL; assert(ref); win = CONTAINER_OF(ref, struct wm_window, ref); dev = win->device; glfwEnable(GLFW_AUTO_POLL_EVENTS); glfwDisable(GLFW_KEY_REPEAT); glfwCloseWindow(); MEM_FREE(dev->allocator, win); WM(device_ref_put(dev)); } /******************************************************************************* * * Window functions. * ******************************************************************************/ EXPORT_SYM enum wm_error wm_create_window (struct wm_device* device, const struct wm_window_desc* desc, struct wm_window** out_win) { struct wm_window* win = NULL; enum wm_error wm_err = WM_NO_ERROR; int width = 0; int height = 0; int mode = 0; if(!device || !out_win || !desc || desc->width > INT_MAX || desc->height > INT_MAX) { wm_err = WM_INVALID_ARGUMENT; goto error; } win = MEM_CALLOC(device->allocator, 1, sizeof(struct wm_window)); if(!win) { wm_err = WM_MEMORY_ERROR; goto error; } WM(device_ref_get(device)); win->device = device; win->fullscreen = desc->fullscreen; ref_init(&win->ref); width = (int)desc->width; height = (int)desc->height; mode = desc->fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW; if(glfwOpenWindow(width, height, 8, 8, 8, 8, 24, 8, mode) == GL_FALSE) { wm_err = WM_INTERNAL_ERROR; goto error; } glfwEnable(GLFW_KEY_REPEAT); glfwDisable(GLFW_AUTO_POLL_EVENTS); exit: if(out_win) *out_win = win; return wm_err; error: if(win) { WM(window_ref_put(win)); win = NULL; } goto exit; } EXPORT_SYM enum wm_error wm_window_ref_get(struct wm_window* win) { if(!win) return WM_INVALID_ARGUMENT; ref_get(&win->ref); return WM_NO_ERROR; } EXPORT_SYM enum wm_error wm_window_ref_put(struct wm_window* win) { if(!win) return WM_INVALID_ARGUMENT; ref_put(&win->ref, release_window); return WM_NO_ERROR; } EXPORT_SYM enum wm_error wm_swap(struct wm_window* win) { if(!win) return WM_INVALID_ARGUMENT; glfwSwapBuffers(); return WM_NO_ERROR; } EXPORT_SYM enum wm_error wm_get_window_desc (struct wm_window* win, struct wm_window_desc* desc) { int width = 0; int height = 0; if(!win || !desc) return WM_INVALID_ARGUMENT; glfwGetWindowSize(&width, &height); assert(width >= 0 && height >= 0); desc->width = (unsigned int)width; desc->height = (unsigned int)height; desc->fullscreen = win->fullscreen; return WM_NO_ERROR; }
C
#include<stdio.h> #define cat(x,y) x##y int main(){ //cat(cat(1,2),3); printf("Output :%d", cat(2,3)); printf("Output2 :%d", cat(1,cat(2,3))); }
C
/* ----------------------------------------------------- * ALF Backend testsuite * Author: Benedikt Huber <benedikt@vmars.tuwien.ac.at> * * pointer1: Pointer Initialization * ----------------------------------------------------- */ struct s1_sub { short lo; short hi; }; struct s1 { char a; short b; int c; long d; long long e; long f; struct s1_sub g; short h; char i; }; struct s2 { char* a; short* b; int* c; long* d; long long* e; long* f; struct s1_sub* g; short* h; char* i; }; char v1 = 1; short v2 = 2; int v3 = 3; long v4 = 4; long long v5 = 5; long v6 = 6; struct s1_sub v7 = {7,7}; short v8 = 8; char v9 = 9; struct s1 w1 = { 1, 2, 3, 4, 5, 6 , {7,7} , 8, 9 }; struct s2 w2 = { &v1, &v2, &v3, &v4, &v5, &v6, &v7, &v8, &v9 }; struct s1 w3; int main() { if(w1.a != *w2.a) return 1; if(w1.b != *w2.b) return 1; if(w1.c != *w2.c) return 1; if(w1.d != *w2.d) return 1; if(w1.e != *w2.e) return 1; if(w1.f != *w2.f) return 1; if(w1.g.lo != w2.g->lo || w1.g.hi != w2.g->hi) return 1; if(w1.h != *w2.h) return 1; if(w1.i != *w2.i) return 1; if(w3.a + w3.b + w3.c + w3.d + w3.e + w3.f + w3.g.lo + w3.g.hi + w3.h + w3.i != 0) return 1; return 0; }
C
#include <stdio.h> #include <winsock2.h> #define BUFFSIZE 1024 // TCP仺С #define TCPQUEUECOUNT 2 // TCPŶӵ #pragma comment(lib, "ws2_32.lib") //ϢreturnԷصϢ char *TPC_Client_Send_and_Recv(char *buf1, int bufLen1, const char *ip, const int port) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0) printf("WSA startup failed\n"); //soocket---------------------------------------------------------- SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); //ͻ˿ɲbind˿ں struct sockaddr_in remote = {0}; remote.sin_family = AF_INET; remote.sin_port = htons(port); remote.sin_addr.s_addr = inet_addr(ip); //ӷ------------------------------------------------------------ int yy = connect(sock, (void *)&remote, sizeof(remote)); //Ϣ-------------------------------------------------------------- send(sock, buf1, bufLen1, 0); //Ϣ-------------------------------------------------------------- char *buf2 = (char *)malloc(BUFFSIZE); recv(sock, buf2, BUFFSIZE, 0); if (WSAGetLastError() != 0) printf("TCPerror = %d\n", WSAGetLastError()); closesocket(sock); WSACleanup(); return buf2; } //Ϣٷͻȥ void TCP_Server_Recv_and_Send(char *buf1, int bufLen1, const int port, char *deal(char *str, char *K1, char *K2), char *K1, char *K2) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0) printf("WSA startup failed\n"); //soocket---------------------------------------------------------- SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); //ЭAF_INETipv4+˿ں struct sockaddr_in s = {0}; s.sin_family = AF_INET; s.sin_port = htons(port); s.sin_addr.s_addr = inet_addr("127.0.0.1"); // //(socket,ipͶ˿)------------------------------------------------ bind(sock, (void *)&s, sizeof(s)); //˿---------------------------------------------------------------- listen(sock, TCPQUEUECOUNT); //Ŷ2tcp //---------------------------------------------------------------- struct sockaddr_in RemoteAddr = {0}; //ԷַϢ int rsocklen = sizeof(RemoteAddr); SOCKET rsock = accept(sock, (void *)&RemoteAddr, &rsocklen); //ʽ //Ϣ---------------------------------------------------------------- recv(rsock, buf1, bufLen1, 0); //Ϣ---------------------------------------------------------------- char *buf2 = deal(buf1, K1, K2); //յϢ send(rsock, buf2, BUFFSIZE, 0); if (WSAGetLastError() != 0) { printf("TCPerror = %d\n", WSAGetLastError()); exit(-1); } closesocket(rsock); closesocket(sock); } /*λȡsocketip? SOCKADDR_IN sockAddr; int iLen=sizeof(sockAddr); getpeername(m_lClient,(struct sockaddr *)&sockAddr,&iLen);//õԶIPַͶ˿ں getsockname(m_lClient,(struct sockaddr *)&sockAddr,&iLen);//õصIPַͶ˿ں strAddr = inet_ntoa(sockAddr.sin_addr);//IP uIPPort = sockAddr.sin_port;//˿ں */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include "node.h" final_node * next_level(final_node *node); int main() { arr_elem root = {.filename = "/", .is_dir = 1, .size = 0}; final_node root_fs = {.child_count = 1, .fs_elements = &root, .next_sibling = &root_fs, .parent = NULL, .parent_index = 0}; size_t child_count; arr_elem *root_elems = list_dir_elem(root.filename, &root, &child_count, &root.size); final_node *iter_node = malloc(sizeof(final_node)); iter_node->child_count = child_count; iter_node->fs_elements = root_elems; iter_node->next_sibling = iter_node; iter_node->parent_index = 0; iter_node->parent = &root_fs; int level = 1; while (iter_node != NULL) { printf("\"%s\" level = %d size in bytes = %llu\n", root.filename, level, root.size); iter_node = next_level(iter_node); level++; } printf("success"); fflush(stdout); scanf("%c", &level); } char * create_full_path_to_parent(final_node *node, size_t *parent_len) { //printf("create full path to parent..."); //создадим полный путь к родителю *parent_len = 0; char *parent_path = malloc(1); parent_path[0] = '\0'; final_node *travers_to_root = node; while (travers_to_root->parent != NULL) { arr_elem *next = travers_to_root->parent->fs_elements + travers_to_root->parent_index; size_t next_part_len = strlen(next->filename); if (next->filename[next_part_len - 1] == '/') next_part_len--; size_t new_parent_len = next_part_len + *parent_len + 1; //1 символ слеша char *new_parent_path = malloc(sizeof(char) * (new_parent_len + 1)); //1 завершающий ноль memcpy(new_parent_path, next->filename, sizeof(char) * next_part_len); new_parent_path[next_part_len] = '/'; memcpy(new_parent_path + next_part_len + 1, parent_path, sizeof(char) * (*parent_len + 1) ); free(parent_path); *parent_len = new_parent_len; parent_path = new_parent_path; travers_to_root = travers_to_root->parent; } return parent_path; } final_node * next_level(final_node *node) { final_node *first = node; size_t alloc_size = 0; char *full_name = malloc(0); final_node *prev_child = NULL; final_node *first_in_next_level = NULL; do { if (node->child_count == 0) { node = node->next_sibling; continue; } size_t parent_len; char *parent_path = create_full_path_to_parent(node, &parent_len); //printf("Iterate through childs of (%.*s)\n", (int)parent_len, parent_path); for (size_t i=0; i<node->child_count; i++) { arr_elem *elem = &node->fs_elements[i]; if (!elem->is_dir) { elem->child = NULL; continue; } elem->child = malloc(sizeof(final_node)); if (first_in_next_level == NULL) { first_in_next_level = elem->child; } elem->child->parent = node; elem->child->parent_index = i; elem->child->next_sibling = NULL; if (prev_child != NULL) { prev_child->next_sibling = elem->child; } size_t next_file_len = strlen(elem->filename); if (parent_len + next_file_len + 1 > alloc_size) { alloc_size = parent_len + next_file_len + 1; free(full_name); full_name = malloc(alloc_size * sizeof(char)); } strcpy(full_name, parent_path); strcpy(full_name + parent_len, elem->filename); elem->child->fs_elements = list_dir_elem(full_name, elem, &elem->child->child_count, &elem->size); //необходимо прибавить полученный размер в байтах ко всем родительским папкам final_node *to_root_for_size = node; if (elem->size != 0) { while (to_root_for_size->parent != NULL) { to_root_for_size->parent->fs_elements[to_root_for_size->parent_index].size += elem->size; to_root_for_size = to_root_for_size->parent; } } prev_child = elem->child; } node = node->next_sibling; } while (node != first); free(full_name); if (prev_child != NULL) { prev_child->next_sibling = first_in_next_level; } return first_in_next_level; }
C
#include <stdio.h> #include <math.h> float squareroot (float a, float b, float c); float mian(){ float a,b,c,d; printf("\n\t ************* ************* ************* ************* *************\n"); printf("\t Type in 3 values foe a,b and c. Type Enter after each input.\n"); printf("\t The square root of a+b+c will be calculated and displayed.\n"); printf("\t Input a:"); scanf("%f", &a ); printf("\t Input b:"); scanf("%f", &b ); printf("\t Input c:"); scanf("%f", &c ); d = squareroot(a,b,c); printf("\n\t a = %f b = %f c = %f",a,b,c); printf("\n\t The square root of a+b+c is %f ",d); printf("\n\t ************* ************* ************* ************* *************\n"); return 0; } float squareroot (float a, float b, float c){ float d = sqrt(a+b+c); return d; }
C
/* reads data from a given collection of pages in collection.txt and generates an "inverted index" that provides a list (set) of urls for every word in a given collection of pages. You need to "normalise" words by removing leading and trailing spaces and converting all characters to lowercases before inserting words in your index. In each list (set), duplicate urls are not allowed. Your program should output this "inverted index" to a file named invertedIndex.txt. The list should be alphabetically ordered, using ascending order. */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include "queue.h" #include "graph.h" #include "set.h" #include "urlReader.h" #define BUFSIZE 1024 //struct to tie "urlXX" file to set of words found in file typedef struct IndexStruct { char* url; // URL in "urlXX" form Set wordSet; // Set of all words found in "urlXX.txt" body } IndexStruct; IndexStruct *newIndex(char *url){ IndexStruct *i; i = malloc(sizeof(IndexStruct)); i->url = url; i->wordSet = newSet(); return i; } void printStringArr(char ** arr); void fillWordSets(IndexStruct * indexArray, int n); void fillStructArr(IndexStruct * indexArray, char **urlArr, int n); Set combineWordSets(IndexStruct * indexArray, int n); char *findRelURLs(char *word, IndexStruct *indArr, int n); int getNumStrInArr(char ** arr); int main(int argc, char const *argv[]) { char *urlColl = getAllURLs(); //get all URLs in collection.txt int numURLTot = numWords(urlColl); //get number of URLs char ** allURLs = parseStringBySpaces(urlColl); //get array of all URLs IndexStruct * wordsInURLs = malloc(numURLTot*sizeof(IndexStruct)); //initialize array to hold all IndexStructs fillStructArr(wordsInURLs, allURLs, numURLTot); //fill array with IndexStructs constructed from the array of all URLs fillWordSets(wordsInURLs, numURLTot); //fill wordSets for each URL Set allWords = combineWordSets(wordsInURLs, numURLTot); //make set of all existing words int nWords = nElems(allWords); //total number of unique words across all files char uniqWords [nWords][20]; // char **test = getElemArr(allWords); // printf("%d\n", nWords); // printStringArr(test); //fills uniqWords in alphabetical ascending order //note that allWords will be empty after loop has run for (int i = 0; i < nWords; i++) { strcpy(uniqWords[i],popString(allWords)); } FILE *f = fopen("invertedIndex.txt", "w"); //file to write to char curWord[20]; for (int i = 0; i < nWords; i++) { strcpy(curWord, uniqWords[i]); //copy word in arr to curWord for readability fprintf(f, "%s %s\n", curWord, findRelURLs(curWord, wordsInURLs, numURLTot)); //print curWord and then any URLs that contain it in text } return 0; } //parameters: word to search for across all URLs, array of IndexStructs, size of array //returns string of all URLs containing 'word' in form "urlXX urlYY urlZZ " char *findRelURLs(char *word, IndexStruct *indArr, int n) { char *relURLs = calloc(500, sizeof(char)); char *curURL; Set curSet; IndexStruct ind; int cnt = 0, len = 0; for (int i = 0; i < n; i++) { ind = indArr[i]; curSet = ind.wordSet; curURL = ind.url; len = strlen(curURL); if(isElem(curSet, word)){ for (int i = 0; i < len; i++) { relURLs[cnt++] = curURL[i]; } relURLs[cnt++] = ' '; } } relURLs[cnt] = '\0'; return relURLs; } //parameters: array of IndexStructs to fill with URLs, array of URLs, size of array of URLs //fills array of IndexStructs void fillStructArr(IndexStruct * indexArray, char **urlArr, int n) { IndexStruct *ind; for (int i = 0; i < n; i++) { ind = newIndex(urlArr[i]); indexArray[i] = *ind; } } //fills all wordSets in indexArray //takes indexArray and size of array as parameters void fillWordSets(IndexStruct * indexArray, int n) { char url[6] = {0}; char words[BUFSIZE]; char **wordArr; int nWords; IndexStruct ind; for (int i = 0; i < n; i++) { ind = indexArray[i]; strcpy(url, ind.url); strcpy(words, wordsInURL(url)); nWords = numWords(words); wordArr = parseStringBySpaces(words); for (int j = 0; j < nWords; j++) { insertInto(indexArray[i].wordSet, wordArr[j]); } } } //takes already filled array of indices //combines already filled sets into superset Set combineWordSets(IndexStruct * indexArray, int n) { Set s = newSet(); char **wordArr; int setSize; IndexStruct ind; for (int i = 0; i < n; i++) { ind = indexArray[i]; wordArr = getElemArr(ind.wordSet); setSize = nElems(ind.wordSet); for (int j = 0; j < setSize; j++) { insertInto(s, wordArr[j]); } } return s; } //prints any array of strings //for testing purposes void printStringArr(char ** arr) { int len = getNumStrInArr(arr); printf("\n\nTesting:%d\n\n", len); for (int i = 0; i < len; i++) { printf("%s\n", arr[i]); } } int getNumStrInArr(char ** arr) { int cnt = 0; while(arr[cnt++] != NULL); return cnt-1; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { char character[] = "ٶ󸶹ٻīŸ"; int inputnum; int ch; FILE* f; f = fopen("character.txt", "wt"); /*for (int i = 0; i < strlen(character);) { fputc(character[i++], f); fputc(character[i++], f); } puts("Է ϷǾϴ.\n"); fclose(f); FILE * f = fopen("character.txt", "rt"); fputs(" ? ", stdout); scanf("%d", &inputnum); for (int i = 0; i < inputnum; i++) { printf("%c", fgetc(f)); printf("%c", fgetc(f)); } puts("\n ϷǾϴ."); fclose(f); */ if (f == NULL) { puts(" 'character.txt' ʾҽϴ."); return -1; } for (int i = 0; i < sizeof(character) - 1; i++) fputc(character[i], f); fclose(f); puts("Է ϷǾϴ."); f = fopen("character.txt", "rt"); if (f == NULL) { puts(" 'character.txt' ʾҽϴ."); return -1; } printf(" ? "); scanf("%d", &inputnum); for (int i = 0; i < inputnum * 2; i++) { ch = fgetc(f); if (ch == EOF) { puts(" Ͽų ߻Ͽϴ."); return -1; } fputc(ch, stdout); } fclose(f); puts(""); puts(" ϷǾϴ."); return 0; }
C
#include "stdio.h" // binary search int search(int a[], int l, int r, int val) { if(l > r) return -1; if(r - l < 2) return a[l] == val ? l : a[r] == val ? r : -1; int mid2 = (l + 2*r)/3, mid1 = (2*l + r)/3; if(a[mid1] >= val) return search(a, l, mid1, val); if(a[mid2] <= val) return search(a, mid2, r, val); return search(a, mid1, mid2, val); } int main(void) { int n, val; printf("Enter n: "); scanf("%d%*c", &n); int a[n + 1], i; // get input for(i = 0; i < n; i++) { printf("Enter single array element in increasing order: "); scanf("%d%*c", a + i); } printf("Enter element to search: "); scanf("%d", &val); // call search int x = search(a, 0, n-1, val); if(x == -1) printf("Not found.\n"); else printf("Found at index %d\n", x); }
C
//The second solution for the problem passes the 2 second barrier easily. //This solutions gets TLE for the last test case #include <stdio.h> #include <string.h> #include <malloc.h> #define li long int #define lli long long int #define setZ(x) memset(x, 0, sizeof(x)); #define givemem(t, n) (t*)malloc(sizeof(t) * (n)) #define si(x) fri(&x) #define pi(x) writeInt(x) #define sli(x) fril(&x) #define slli(x) frill(&x) #define gc getchar_unlocked #define pc putchar_unlocked #define fl(i, val, n) for(i = (val);i < (n);i++) #define fln(i, val, n) for(i = (val);i > (n);i--) inline void writeInt(long long int n) { long long int N = n, rev, count = 0; rev = N; if (N == 0) { pc('0'); return; } while ((rev % 10) == 0) { count++; rev /= 10; } //obtain the count of the number of 0s rev = 0; while (N != 0) { rev = (rev << 3) + (rev << 1) + N % 10; N /= 10; } //store reverse of N in rev while (rev != 0) { pc(rev % 10 + '0'); rev /= 10; } while (count--) { pc('0'); } } inline void frs(char * str) { register char c = 0; register int i = 0; while (c < 33) c = gc(); while (c != '\n') { str[i] = c; c = gc(); i = i + 1; } str[i] = '\0'; } inline void fril(long int * x) { register int c = gc(); *x = 0; int neg = 0; for(; ((c < 48 || c > 57) && c != '-'); c = gc()); if(c == '-') { neg = 1; c = gc(); } for(; c > 47 && c < 58 ; c = gc()) { *x = ((*x) << 1) + ((*x) << 3) + c - 48; } if(neg) *x = -(*x); } inline void frill(long long int * x) { register int c = gc(); *x = 0; int neg = 0; for(; ((c < 48 || c > 57) && c != '-'); c = gc()); if(c == '-') { neg = 1; c = gc(); } for(; c > 47 && c < 58 ; c = gc()) { *x = ((*x) << 1) + ((*x) << 3) + c - 48; } if(neg) *x = -(*x); } inline void fri(int * x) { register int c = gc(); *x = 0; int neg = 0; for(; ((c < 48 || c > 57) && c != '-'); c = gc()); if(c == '-') { neg = 1; c = gc(); } for(; c > 47 && c < 58 ; c = gc()) { *x = ((*x) << 1) + ((*x) << 3) + c - 48; } if(neg) *x = -(*x); } //lli segTree[2100000]; //li lazy[2100000]; lli * segTree; li * lazy; void update_tree(lli seg, li s, li e, li us, li ue) { lli left, right; li mid; left = (seg << 1) + 1; right = left + 1; if(lazy[seg]) { segTree[seg] += (long long int)(lazy[seg] * (e - s + 1)); if(s != e) { lazy[left] += lazy[seg]; lazy[right] += lazy[seg]; } lazy[seg] = 0; } if(us > e || ue < s) return; if(s >= us && e <= ue) { segTree[seg] += (long long int)(e - s + 1); if(s != e) { lazy[left]++; lazy[right]++; } } else { mid = (s + e) / 2; update_tree(left, s, mid, us, ue); update_tree(right, mid + 1, e, us, ue); segTree[seg] = segTree[left] + segTree[right]; } } lli query_tree(lli seg, li s, li e, li qs, li qe) { li mid; lli left, right; left = (seg << 1) + 1; right = left + 1; if(lazy[seg]) { segTree[seg] += (long long int)(lazy[seg] * (e - s + 1)); if(s != e) { lazy[left] += lazy[seg]; lazy[right] += lazy[seg]; } lazy[seg] = 0; } if(qs > e || qe < s) return 0; if(s >= qs && e <= qe) return segTree[seg]; else { mid = (s + e) / 2; return query_tree(left, s, mid, qs, qe) + query_tree(right, mid + 1, e, qs, qe); } } li ih[1000005], il[1000005]; int main() { int t; li n, h, i, zn, zh; lli maxSpaces, emptySpaces; si(t); while(t--) { maxSpaces = 0; //setZ(lazy); lazy = (li *)calloc(2098000, sizeof(li)); segTree = (lli *)calloc(2098000, sizeof(lli)); //setZ(segTree); sli(n); sli(h); fl(i, 0, n) { sli(il[i]); sli(ih[i]); } zn = n - 1; zh = h - 1; fl(i, 0, n) update_tree(0, 0, zn, il[i], ih[i]); fl(i, 0, n - zh) { emptySpaces = query_tree(0, 0, zn, i, i + zh); if(maxSpaces < emptySpaces) maxSpaces = emptySpaces; } pi((long long int)((long long int)n * h - maxSpaces)); pc('\n'); free(lazy); free(segTree); } return 0; }
C
// ENCONTRAR EL MAYOR NUMERO DE UN VECTOR/ARRAY /* Realizar un algoritmo que permita la carga de 5 numeros en un vector. Una vez cargados debe determinar cual es el mayor de ellos. */ #include <stdio.h> main() { // SET UP VARIABLES int nums[5] = {12, 50, 73, 84, 16}; int mayor = -192000; int ctr; int position = 0; for (ctr = 0; ctr < 5; ctr++) { if (nums[ctr] > mayor) { mayor = nums[ctr]; position = ctr; } } printf("El numero mayor es: %d y fue encontrado en la posicion %d\n\n", mayor, position); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_x_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ncliff <ncliff@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/10 14:36:32 by ncliff #+# #+# */ /* Updated: 2021/01/26 13:24:58 by ncliff ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" char ft_printf_hex(unsigned int hex, t_prnt **t_arg) { if (hex < 10) return ((char)hex + '0'); else if (hex == 10) return (((*t_arg)->arg == 'x' || (*t_arg)->arg == 'p') ? 'a' : 'A'); else if (hex == 11) return (((*t_arg)->arg == 'x' || (*t_arg)->arg == 'p') ? 'b' : 'B'); else if (hex == 12) return (((*t_arg)->arg == 'x' || (*t_arg)->arg == 'p') ? 'c' : 'C'); else if (hex == 13) return (((*t_arg)->arg == 'x' || (*t_arg)->arg == 'p') ? 'd' : 'D'); else if (hex == 14) return (((*t_arg)->arg == 'x' || (*t_arg)->arg == 'p') ? 'e' : 'E'); else if (hex == 15) return (((*t_arg)->arg == 'x' || (*t_arg)->arg == 'p') ? 'f' : 'F'); return (0); } static char *ft_hex_rev(char *revhex, int i) { char *hex; int n; n = 0; if (!(hex = (char *)malloc((i + 1) * sizeof(char)))) return (NULL); i--; while (i >= 0) { hex[n] = revhex[i]; n++; i--; } hex[n] = '\0'; return (hex); } static char *ft_hex_x(unsigned int hexin, t_prnt **t_args) { char *hex; char *revhex; int i; i = 0; if (hexin == 0) { if (!(hex = (char *)malloc(2 * sizeof(char)))) return (NULL); hex[0] = '0'; hex[1] = 0; return (hex); } if (!(revhex = (char *)malloc(16 * sizeof(char)))) return (NULL); while (hexin > 0) { revhex[i] = ft_printf_hex(hexin % 16, t_args); hexin /= 16; i++; } revhex[i] = 0; hex = ft_hex_rev(revhex, i); free(revhex); return (hex); } int ft_printf_h(t_prnt **l_args, va_list args, int point) { char *num; int i; if (!(num = ft_hex_x(va_arg(args, unsigned int), l_args))) return (-1); while (num[point] != '\0') point++; if ((*l_args)->acacy > (-1)) { if ((*num) == '0' && (*l_args)->acacy == 0) point = 0; point = acacy_d((*l_args)->acacy, point, &num); } if ((*l_args)->widht > point && (*l_args)->flag != '-') return (widht_d((*l_args)->widht, point, &num, l_args)); else if ((*l_args)->widht > point && (*l_args)->flag == '-') return (widht_d_minus((*l_args)->widht, point, num)); else { i = write(1, num, point); free(num); return (i); } return (0); }
C
#include <stdio.h> #include <time.h> int recursFib(int n) { if (n > 25) { return -1; } if (n < 2) { return n; } return recursFib(n - 1) + recursFib(n - 2); } int iterateFib(int n) { if (n > 46) { return -1; } int a = 0, b = 1, c; for (int i = 0; i < n; i++) { c = a; a = a + b; b = c; } return a; } int proRecursFib(int a, int b, int n) { if (n > 46) { return -1; } if (n >= 1) { return proRecursFib(a + b, a, n - 1); } return a; } void main() { iterateFib(10); recursFib(10); proRecursFib(0, 1, 10); } // printf("F(40)=:\n"); // time_t start, end; // start = clock(); // printf("递推: %lld ", ddFib(a)); // end = clock(); // printf("time=%d\n", end - start); // start = clock(); // printf("普通递归:%lld ", Fib(a)); // end = clock(); // printf("time=%d\n", end - start); // start = clock(); // printf("优化递归: %lld ", newFib(0, 1, a)); // end = clock(); // printf("time=%d\n", end - start); // a = 10000; // printf("F(1000)=:\n"); // start = clock(); // printf("递推: %lld ", ddFib(a)); // end = clock(); // printf("time=%d\n", end - start); // // start = clock(); // // printf("普通递归:%lld ", Fib(a)); // // end = clock(); // // printf("time=%d\n", end - start); // start = clock(); // printf("优化递归: %lld ", newFib(0, 1, a)); // end = clock(); // printf("time=%d\n", end - start);
C
#include <unistd.h> #include <stdio.h> #include <sqlite3.h> #include "macro.h" #include "db.h" void print_sql_error(sqlite3* db, int rc) { DEBUG("SQL Code: %i, %s\n", rc, sqlite3_errmsg(db)); } int create_table(sqlite3* db, const char* sql_stmt) { sqlite3_stmt* stmt = NULL; int rc = sqlite3_prepare_v2(db, sql_stmt, -1, &stmt, NULL); if(!rc) { rc = sqlite3_step(stmt); sqlite3_finalize(stmt); if(rc == SQLITE_DONE) { rc = SQLITE_OK; } } if(rc) { DEBUG("Failed to create table. "); print_sql_error(db, rc); } return rc; } int open_database(const char* db_file, sqlite3** db) { char* sql_err_msg = 0; int sql_rc = sqlite3_open_v2(db_file, db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOFOLLOW, NULL); if(sql_rc) { fprintf(stderr, "Unable to open \"%s\" database %s\n", db_file, sqlite3_errmsg(*db)); return 1; } return 0; } int prepare_database(sqlite3* db) { int sql_rc = create_table(db, CREATE_SHARE_REFERENCES_TABLE); if(!sql_rc) sql_rc = create_table(db, CREATE_DAILY_SHARE_VALUE_TALBE); if(sql_rc) { sqlite3_close(db); return 1; } return 0; }
C
/* write a c program that takes 4 numbers from user and swap it between num1 & num2, num3 and num4. */ #include<stdio.h> void main() { float num1, num2, num3, num4, temp1, temp2; printf("Enter number1: "); scanf("%f", &num1); printf("Enter number2: "); scanf("%f", &num2); printf("Enter number3: "); scanf("%f", &num3); printf("Enter number4: "); scanf("%f", &num4); temp1 = num1; num1 = num2; num2 = temp1; temp2 = num3; num3 = num4; num4 = temp2; printf("Number1 is: %.2f\n", num1); printf("Number2 is: %.2f\n", num2); printf("Number3 is: %.2f\n", num3); printf("Number4 is: %.2f", num4); return 0; }
C
/*-------------------------------------------------------------------------- * headers à inclure afin de pouvoir utiliser divers appels systèmes * -----------------------------------------------------------------------*/ #include <stdio.h> /* pour printf() and co */ #include <stdlib.h> /* pour exit() */ #include <errno.h> /* pour errno and co */ #include <sys/types.h> /* pour pid_t, open() et kill()*/ #include <sys/stat.h> /* pour open() */ #include <fcntl.h> /* pour open() */ #include <unistd.h> /* pour write() et close()*/ #include <signal.h> /* pour kill() */ /*-------------------------------------------------------------------------- * Fonction principale * -----------------------------------------------------------------------*/ int main(void) { int desc; pid_t pid; desc = open("/tmp/vent",O_RDONLY); if (desc == -1) {perror("Echec open "); exit(errno); } ssize_t res=read(desc,&pid,sizeof(pid_t)); if(res==-1) {perror("Echec read "); exit(errno); } close(desc); printf("Je vise %d\n",(int)pid); sleep(5); printf("pan!\n"); return EXIT_SUCCESS; }
C
#include <stdio.h> // Method 1 typedef struct _Location { int x; int y; } Location; // <- ALWAYS remember to put a semicolon here. // Over here, i combined the struct declaration and typedef statement. This is probably the way of declaration you will be using the most, but practice caution when you do so. In fact, in this declaration, you can also omit _Location right after struct, and it will still work. But that's a bad practice so do not do that. int main(){ Location A; // As you can see, over here you don't have to write "struct" before Location anymore. A.x = 10; A.y = 20; printf("%d %d\n", A.x, A.y); return 0; }
C
//Definicao da estrutura aluno typedef struct aluno { int id; char nome[20]; char email[40]; int idade; char status; } aluno; //Definicao dos prototipos das funcoes aluno * recebeInfoAluno(int id); node * cadastrarAluno(node *raiz, int *id); node * removerAluno(node *raiz); void exibirListaAlunos(node *raiz); void exibirResumo(); int insereRegistro(aluno *aux); void inativaRegistro(int rid); void exibirRegistro(int rid); //Funcao que recebe as informacoes do aluno aluno * recebeInfoAluno(int id){ aluno *novo; novo = (aluno *) malloc(sizeof(aluno)); //Limpa o buffer getchar(); printf("Digite o nome do aluno: "); scanf("%[^\n]", novo->nome); //Limpa o buffer getchar(); printf("Digite o email do aluno: "); scanf("%[^\n]", novo->email); printf("Digite a idade do aluno: "); scanf("%d", &novo->idade); novo->id = id; novo->status = 'A'; return novo; } //Funcao principal de cadastro de aluno node * cadastrarAluno(node *raiz, int *id){ //Declaracao de variaveis aluno *novo; int rid; //Envia o valor do id do novo registro que sera inserido novo = recebeInfoAluno(*id); //Exibe o ID do aluno ao usuario printf("ID do Aluno: %d\n", novo->id); //Avanca o valor do id *id = *id + 1; //Insere no arquivo do banco de dados (TXT) rid = insereRegistro(novo); //Insere o registro na arvore raiz = insert(raiz, novo->id, rid); return raiz; } //Funcao principal de remocao de aluno node * removerAluno(node *raiz){ //Declaracao de variaveis int id; record *registro = NULL; node *noFolha = NULL; //Recebendo o ID do aluno printf("Digite o ID do aluno que deseja remover: "); scanf("%d", &id); //Buscando o ID e recebendo a linha que se encontra o registro //Envia raiz, id do Aluno, false e a posicao de um ponteiro do node da folha que sera apagado registro = find(raiz, id, false, &noFolha); //Verifica se o registro existe if (registro == NULL){ printf("Nenhum aluno com o ID digitado.\n"); } else { //Inativa o registro no arquivo inativaRegistro(registro->value); //Deleta o registro na arvore raiz = delete_entry(raiz, noFolha, id, registro); } return raiz; } //Funcao que exibe os registros ativos dos alunos void exibirListaAlunos(node *raiz){ //Declaracao de variaveis node *aux = raiz; int i; record *registro = NULL; //Verifica se a arvore esta vazia if (raiz == NULL) { printf("Nenhum aluno registrado.\n"); } else{ //Percorrendo a arvore para chegar na primeira folha while(!aux->is_leaf){ aux = aux->pointers[0]; } while(true){ for(i=0; i < aux->num_keys; i++){ //Exibe o registro do aluno registro = (record *) aux->pointers[i]; exibirRegistro(registro->value); //Exibindo o ID para teste printf(" %d) ", aux->keys[i]); } if (aux->pointers[order - 1] != NULL) { printf(" | "); aux = aux->pointers[order - 1]; } else break; } printf("\n"); } } //Funcao que exibe o resumo void exibirResumo(){ puts("Funcionalidade nao implementada."); } //Funcao que insere um registro no arquivo int insereRegistro(aluno *aux){ //Variaveis auxiliares de leitura int Linha=0, linha=0, id=0, x=0, idade; char nome[100], email[100], status; //Abrindo arquivo em questão FILE * Arquivo; Arquivo = fopen("bd.txt", "a+"); if(Arquivo != NULL){ rewind(Arquivo); while(!feof(Arquivo)){ x = fscanf(Arquivo, "%d %d %s %d %s %c\n", &Linha, &id, nome, &idade, email, &status); if(x > 0){ linha++; } } linha++; x = fprintf(Arquivo, "%d %d %s %d %s %c\n", linha, aux->id, aux->nome, aux->idade, aux->email, 'A'); if(x < 0){ puts("+====================================+"); puts("| !! ERROR: Dados nao registrado !! |"); puts("+====================================+"); } else{ puts("\n> DADOS REGISTRADOS COM SUCESSO!"); } fclose(Arquivo); } else{ puts("+====================================+"); puts("| !! ERROR: Arquivo nao encontrado ! |"); puts("+====================================+"); } return linha; return 0; } //Funcao que inativa uma linha do arquivo void inativaRegistro(int rid){ char oldname[] = "bd.txt"; char newname[] = "temp.txt"; //Abre o arquivo atual de registros FILE *Ler = fopen(oldname,"r"); //Abre o arquivo auxiliar de registros FILE *Novo = fopen(newname,"w+"); //Variaveis auxiliares de leitura int Linha=0, linha=0, id=0, x=0, idade, Status; char nome[100], email[100], status; //Se o arquivo existir if(Ler != NULL){ rewind(Ler); //laço para percorrer todo o arquivo while(!feof(Ler)){ //leitura dos dados do arquivo atual de registros x = fscanf(Ler, "%d %d %s %d %s %c\n", &Linha, &id, nome, &idade, email, &status); //Verifica se a leitura foi bem sucedida if(x > 0){ linha++; //verifica se a linha lida é a desejada if(Linha == rid){ Status = 1; //Imprime o registro atualizado no novo arquivo fprintf(Novo,"%d %d %s %d %s %c\n",linha, id, nome, idade, email, 'I'); } else{ //Copia o registro para o novo arquivo fprintf(Novo,"%d %d %s %d %s %c\n",linha, id, nome, idade, email, status); } } } } else{ //caso o arquivo não exista puts("ERRO: Não foi possível abrir os registros!\n"); return; } //fecha os arquivos abertos fclose(Ler); fclose(Novo); //remoção dos registros antigos Status = remove(oldname); //renomeia o registro auxiliar para o nome padrão Status = rename(newname, oldname); //caso a remoção seja bem sucedida if(Status == 0) return; else{ //caso ocorra algum erro na remoção dos registros antigos puts("\nNão foi possível remover o registro no arquivo!\n"); return; } } //Funcao que exibe o registro de um aluno void exibirRegistro(int rid){ printf("(%d", rid); }
C
#include <stdio.h> #include <stdlib.h> char Reverse_String(char string[]) { int ret = sizeof(string) / sizeof(string[0]); for (int i = 1; i <= ret; i++) { return Reverse_String; } } int main() { int i; char string[] = "abcd"; printf("%c\t", string[i]); system("pause"); return 0; }
C
// Header for platform independant serial communications // // senseitg@gmail.com 2012-Nov-26 #include <stdint.h> #include <stdbool.h> // enumerate serial devices // fp_enum is callback to receive each device void senum(void (*fp_enum)(char *name,char *device)); // open serial port // device has system dependant form // returns true if successful bool sopen(char* device); // configure serial port // fmt has form "baud,parity,databits,stopbit", ie: "9600,N,8,1" // returns true if successful bool sconfig(char* fmt); // get number of bytes available int32_t speek(void); // read from serial port // returns bytes actually read int32_t sread(void *p_read,uint16_t i_read); // write to serial port int32_t swrite(void* p_write,uint16_t i_write); // close serial port bool sclose();
C
#include "led.h" #include "delay.h" #include "sys.h" #include "usart.h" #include "oled.h" #include "csb.h" u32 Distance; float m1,m2; void Display(void); int main(void) { delay_init(72); //ʱʼ uart_init(72,9600); //ڳʼΪ9600 LED_Init(); //ʼLEDӵӲӿ OLED_Init(); OLED_Clear(); TIM3_Cap_Init(0XFFFF,72-1); while(1) { Read_Distane(); m1=Distance/10; m2=Distance%10; if(m1>3000) { m1=0; } if(m1<5) { Beep=0; } if(m1>=5) { Beep=1; } Display(); } } void Display() { OLED_ShowCHinese(0,0,0); OLED_ShowCHinese(16,0,1); OLED_ShowChar(32,0,':',16); OLED_ShowNum(40,0,m1,4,16); OLED_ShowChar(72,0,'.',16); OLED_ShowNum(80,0,m2,1,16); OLED_ShowString(88,0,"CM",16); OLED_ShowCHinese(0,2,5); OLED_ShowCHinese(16,2,6); OLED_ShowNum(32,2,141,3,16); }
C
/* ** peephole optimizer ** ** basically a simple text replacement processor */ char nooptimize = 0; /* this flag disables optimization if set (by debug) */ peephole(ptr) char *ptr; { while(*ptr) { char *ptr1; ptr1 = ptr; /* save for later compare */ /* ** if optimization is disabled, skip everything ** all patterns start with tab, so look for one */ while(*ptr && (*ptr != '\t'|| nooptimize)) cout(*ptr++,output); if(streq(ptr, "\tLEA AX,[BP]")) ptr = optim1(ptr, 12); if(streq(ptr, "\tMOV AX,1\n")) ptr = optim3(ptr, 10); if(streq(ptr, "\tMOV AX,")) ptr = optim4(ptr, 8); if(streq(ptr, "\tPUSH AX\n\tMOV AX,")) ptr = optim5(ptr, 17); if(streq(ptr, "\tPUSH AX\n\tLEA AX,[BP]")) ptr = optim6(ptr, 21); if(streq(ptr, "\tMOV BX,DX\n\tPOP BX\n")) ptr = optim7(ptr, 19); if(streq(ptr, "\tMOV BX,")) ptr = optim8(ptr, 8); if(streq(ptr, "\tJNZ $+5\n")) ptr = optim9(ptr+9, "JNZ $+"); if(streq(ptr, "\tJZ $+5\n")) ptr = optim9(ptr+8, "JZ $+"); /* additional optimizing logic goes here */ if(ptr == ptr1) cout(*ptr++, output); } } /* ** optimize strings beginning "\tLEA AX,[BP]" */ optim1(ptr, bump) char *ptr; int bump; { char offset[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save offset from LEA */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tMOV BX,AX\n\tMOV SI,AX\n\tMOV AX,[SI]\n")) ptr = optim11(ptr, bump+35, offset); else if(streq(ptr1, "\tMOV SI,AX\n\tMOV AX,[SI]\n")) ptr = optim12(ptr, bump+24, offset); else if(streq(ptr1, "\tMOV SI,AX\n\tMOV AL,[SI]\n")) { ot("MOV AL,[BP]"); outstr(offset); outstr(" ;optim1 - 1"); nl(); ptr = ptr1 + 24; } else if(streq(ptr1, "\tPUSH AX\n\tLEA AX,[BP]")) ptr = optim13(ptr, bump+21, offset); else if(streq(ptr1, "\tPUSH AX\n\tMOV AX,")) ptr = optim14(ptr, bump+17, offset); else if(streq(ptr1, "\tPUSH AX\n\tMOV SI,AX\n")) ptr = optim15(ptr, bump+20, offset); return ptr; } /* ** optimize strings beginning ** "\tLEA AX,[BP]xxxx\n\tMOV BX,AX\n\tMOV SI,AX\n\tMOV AX,[SI]\n" */ optim11(ptr, bump, offset) char *ptr, offset[]; int bump; { char *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tINC AX\n\tMOV [BX],AX\n")) ptr = optim111(ptr, bump+21, offset); else if(streq(ptr1, "\tDEC AX\n\tMOV [BX],AX\n")) ptr = optim112(ptr, bump+21, offset); return ptr; } /* ** optimize strings beginning ** "\tLEA AX,[BP]xxxx\n\tMOV BX,AX\n\tMOV SI,AX\n\tMOV AX,[SI]\n" ** "\tINC AX\n\tMOV [BX],AX\n" */ optim111(ptr, bump, offset) char *ptr, offset[]; int bump; { char *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tDEC AX\n\tMOV SI,AX\n\tMOV AL,[SI]\n")) { if(ptr1[32]) { /* if not end of expression */ ot("MOV BX,[BP]"); outstr(offset); nl(); ot("INC WORD PTR [BP]"); outstr(offset); nl(); ol("MOV AL,[BX] ;optim111 - 1"); ptr = ptr1 + 32; } else ptr = opti1111(ptr, bump+32, offset); } else if(streq(ptr1, "\tDEC AX\n")) { if(ptr1[8]) { /* if not end of expression */ ot("MOV AX,[BP]"); outstr(offset); nl(); ot("INC WORD PTR [BP]"); outstr(offset); outstr(" ;optim111 - 2"); nl(); ptr = ptr1 + 8; } else ptr = opti1111(ptr, bump+8, offset); } else if(streq(ptr1, "\tMOV SI,AX\n\tMOV AL,[SI]\n")) { if(ptr1[8]) { /* if not end of expression */ ot("INC WORD PTR [BP]"); outstr(offset); nl(); ot("MOV BX,[BP]"); outstr(offset); nl(); ol("MOV AL,[BX] ;optim111 - 3"); ptr = ptr1 + 24; } else ptr = opti1111(ptr, bump+24, offset); } else { if(ptr1[0]) { /* if not end of expression */ ot("INC WORD PTR [BP]"); outstr(offset); nl(); ot("MOV AX,[BP]"); outstr(offset); outstr(" ;optim111 - 4"); nl(); ptr = ptr1; } else ptr = opti1111(ptr, bump, offset); } return ptr; } /* ** optimize "++" operators on simple auto variables with no destination */ opti1111(ptr, bump, offset) char *ptr, offset[]; int bump; { ot("INC WORD PTR [BP]"); outstr(offset); outstr(" ;opti1111 - 1"); nl(); return ptr + bump; } /* ** optimize strings beginning ** "\tLEA AX,[BP]xxxx\n\tMOV BX,AX\n\tMOV SI,AX\n\tMOV AX,[SI]\n" ** "\tDEC AX\n\tMOV [BX],AX\n" */ optim112(ptr, bump, offset) char *ptr, offset[]; int bump; { char *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tINC AX\n\tMOV SI,AX\n\tMOV AL,[SI]\n")) { if(ptr1[32]) { /* if not end of expression */ ot("MOV BX,[BP]"); outstr(offset); nl(); ot("DEC WORD PTR [BP]"); outstr(offset); nl(); ol("MOV AL,[BX] ;optim112 - 1"); ptr = ptr1 + 32; } else ptr = opti1121(ptr, bump+32, offset); } else if(streq(ptr1, "\tINC AX\n")) { if(ptr1[8]) { /* if not end of expression */ ot("MOV AX,[BP]"); outstr(offset); nl(); ot("DEC WORD PTR [BP]"); outstr(offset); outstr(" ;optim112 - 2"); nl(); ptr = ptr1 + 8; } else ptr = opti1121(ptr, bump+8, offset); } else if(streq(ptr1, "\tMOV SI,AX\n\tMOV AL,[SI]\n")) { if(ptr1[24]) { /* if not end of expression */ ot("DEC WORD PTR [BP]"); outstr(offset); nl(); ot("MOV BX,[BP]"); outstr(offset); nl(); ol("MOV AL,[BX] ;optim112 - 3"); ptr = ptr1 + 24; } else ptr = opti1121(ptr, bump+24, offset); } else { if(ptr1[0]) { /* if not end of expression */ ot("DEC WORD PTR [BP]"); outstr(offset); nl(); ot("MOV AX,[BP]"); outstr(offset); outstr(" ;optim112 - 4"); nl(); ptr = ptr1; } else ptr = opti1121(ptr, bump, offset); } return ptr; } /* ** optimize "--" operators on simple auto variables with no destination */ opti1121(ptr, bump, offset) char *ptr, offset[]; int bump; { ot("DEC WORD PTR [BP]"); outstr(offset); outstr(" ;opti1121 - 1"); nl(); return ptr + bump; } /* ** optimize strings beginning ** "\tLEA AX,[BP]xxxx\n\tMOV SI,AX\n\tMOV AX,[SI]\n" */ optim12(ptr, bump, offset) char *ptr, offset[]; int bump; { char *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tMOV SI,AX\n\tMOV AX,[SI]\n")) { ot("MOV SI,[BP]"); outstr(offset); nl(); ol("MOV AX,[SI] ;optim12 - 1"); ptr = ptr1 + 24; } else if(streq(ptr1, "\tMOV SI,AX\n\tMOV AL,[SI]\n\tCBW\n\tAND AX,AX\n")) { ot("MOV SI,[BP]"); outstr(offset); nl(); ol("CMP BYTE PTR [SI],0 ;optim12 - 2"); ptr = ptr1 + 40; } else if(streq(ptr1, "\tMOV SI,AX\n\tMOV AL,[SI]\n")) { ot("MOV SI,[BP]"); outstr(offset); nl(); ol("MOV AL,[SI] ;optim12 - 3"); ptr = ptr1 + 24; } else { ot("MOV AX,[BP]"); outstr(offset); outstr(" ;optim12 - 4"); nl(); ptr = ptr1; } return ptr; } /* ** optimize strings beginning "\tLEA AX,[BP]xxxx\n\tPUSH AX\n\tLEA AX,[BP]" */ optim13(ptr, bump, offset) char *ptr, offset[]; int bump; { char offset2[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset2; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save source from LEA */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tMOV SI,AX\n\tMOV AX,[SI]\n\tPOP BX\n\tMOV [BX],AX\n")) { ot("MOV AX,[BP]"); outstr(offset2); nl(); ot("MOV [BP]"); outstr(offset); outstr(",AX ;optim13 - 1"); nl(); ptr = ptr1 + 45; } else if(streq(ptr1, "\tMOV SI,AX\n\tMOV AL,[SI]\n\tCBW\n\tPOP BX\n\tMOV [BX],AL\n")) { ot("MOV AL,[BP]"); outstr(offset2); nl(); ol("CBW"); ot("MOV [BP]"); outstr(offset); outstr(",AL ;optim13 - 2"); nl(); ptr = ptr1 + 50; } return ptr; } /* ** optimize strings beginning "\tLEA AX,[BP]xxxx\n\tPUSH AX\n\tMOV AX," */ optim14(ptr, bump, offset) char *ptr, offset[]; int bump; { char offset2[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset2; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save source from MOV */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tPOP BX\n\tMOV [BX],AX\n")) { ot("MOV AX,"); outstr(offset2); nl(); ot("MOV [BP]"); outstr(offset); outstr(",AX ;optim14 - 1"); nl(); ptr = ptr1 + 21; } else if(streq(ptr1, "\tPOP BX\n\tMOV [BX],AL\n")) { ot("MOV AX,"); outstr(offset2); nl(); ot("MOV [BP]"); outstr(offset); outstr(",AL ;optim14 - 2"); nl(); ptr = ptr1 + 21; } return ptr; } /* ** optimize strings beginning ** "\tLEA AX,[BP]xxxx\n\tPUSH AX\n\tMOV SI,AX\n" */ optim15(ptr, bump, offset) char *ptr, offset[]; int bump; { char *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tMOV AX,[SI]\n")) { ot("LEA SI,[BP]"); outstr(offset); nl(); ol("PUSH SI"); ol("MOV AX,[SI] ;optim15 - 1"); ptr = ptr1 + 13; } else if(streq(ptr1, "\tMOV AL,[SI]\n")) { ot("LEA SI,[BP]"); outstr(offset); nl(); ol("PUSH SI"); ol("MOV AL,[SI] ;optim15 - 2"); ptr = ptr1 + 13; } return ptr; } /* ** optimize strings beginning "\tMOV AX,1\n" */ optim3(ptr, bump) char *ptr; int bump; { char *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tJE $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n") | streq(ptr1, "\tJZ $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n")) { ol(";optim3 - 1"); ptr = optim9(ptr1+36, "JZ $+"); } else if(streq(ptr1, "\tJNE $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n") | streq(ptr1, "\tJNZ $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n")) { ol(";optim3 - 1B"); ptr = optim9(ptr1+37, "JNZ $+"); } else if(streq(ptr1, "\tJG $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n")) { ol(";optim3 - 2"); ptr = optim9(ptr1+36, "JG $+"); } else if(streq(ptr1, "\tJL $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n")) { ol(";optim3 - 3"); ptr = optim9(ptr1+36, "JL $+"); } else if(streq(ptr1, "\tJGE $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n")) { ol(";optim3 - 4"); ptr = optim9(ptr1+37, "JGE $+"); } else if(streq(ptr1, "\tJLE $+3\n\tDEC AX\n\tAND AX,AX\n\tJNZ $+5\n")) { ol(";optim3 - 5"); ptr = optim9(ptr1+37, "JLE $+"); } return ptr; } /* ** optimize strings beginning "\tMOV AX," */ optim4(ptr, bump) char *ptr; int bump; { char offset[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save source from MOV */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tINC AX\n\tMOV ")) ptr = optim41(ptr, bump+13, offset); else if(streq(ptr1, "\tDEC AX\n\tMOV ")) ptr = optim42(ptr, bump+13, offset); else if(streq(ptr1, "\tMOV BX,")) ptr = optim43(ptr, bump+8, offset); return ptr; } /* ** optimize strings beginning "\tMOV AX,xxxx\n\tINC AX\n\tMOV " */ optim41(ptr, bump, offset) char *ptr, offset[]; int bump; { char *ptr1, *ptr2, *ptr3; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, offset)) { ptr3 = offset; while(*ptr3++) {++ptr1; ++bump;} /* skip over value */ if(streq(ptr1, ",AX\n\tDEC AX\n")) { if(ptr1[12]) { ot("MOV AX,"); outstr(offset); nl(); ot("INC "); outstr(offset); outstr(" ;optim41 - 1"); nl(); ptr = ptr1 + 12; } else ptr = optim411(ptr, bump+12, offset); } else if(streq(ptr1, ",AX\n")) { if(ptr1[4]) { ot("INC "); outstr(offset); nl(); ot("MOV AX,"); outstr(offset); outstr(" ;optim41 - 2"); nl(); ptr = ptr1 + 4; } else ptr = optim411(ptr, bump+4, offset); } } return ptr; } /* ** optimize "++" operators on simple static variables with no destination */ optim411(ptr, bump, offset) char *ptr, offset[]; int bump; { ot("INC "); outstr(offset); outstr(" ;optim411 - 1"); nl(); return ptr + bump; } /* ** optimize strings beginning "\tMOV AX,xxxx\n\tDEC AX\n\tMOV " */ optim42(ptr, bump, offset) char *ptr, offset[]; int bump; { char *ptr1, *ptr2, *ptr3; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = ptr; /* save for compare */ if(streq(ptr1, offset)) { ptr3 = offset; while(*ptr3++) {++ptr1; ++bump;} /* skip over value */ if(streq(ptr1, ",AX\n\tINC AX\n")) { if(ptr1[12]) { ot("MOV AX,"); outstr(offset); nl(); ot("DEC "); outstr(offset); outstr(" ;optim42 - 1"); nl(); ptr = ptr1 + 12; } else ptr = optim421(ptr, bump+12, offset); } else if(streq(ptr1, ",AX\n")) { if(ptr1[4]) { ot("DEC "); outstr(offset); nl(); ot("MOV AX,"); outstr(offset); outstr(" ;optim42 - 2"); nl(); ptr = ptr1 + 4; } else ptr = optim421(ptr, bump+4, offset); } } return ptr; } /* ** optimize "--" operators on simple auto variables with no destination */ optim421(ptr, bump, offset) char *ptr, offset[]; int bump; { ot("DEC "); outstr(offset); outstr(" ;optim421 - 1"); nl(); return ptr + bump; } /* ** optimize strings beginning "\tMOV AX,xxxx\n\tMOV BX," */ optim43(ptr, bump, offset) char *ptr, offset[]; int bump; { char offset2[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset2; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save source from MOV */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\n\tADD AX,BX\n\tMOV SI,AX\n\tMOV AX,[SI]\n")) { ot("MOV BX,"); outstr(offset); nl(); ot("ADD BX,"); outstr(offset2); nl(); ol("MOV AX,[BX] ;optim43 - 1"); ptr = ptr1 + 36; } return ptr; /* "MOV BX," may be separately optimizable */ } /* ** optimize strings beginning "\tPUSH AX\n\tMOV AX," */ optim5(ptr, bump) char *ptr; int bump; { char offset[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save source from MOV */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tPOP BX\n\tADD AX,BX\n")) { ot("ADD AX,"); outstr(offset); outstr(" ;optim5 - 1"); nl(); ptr = ptr1 + 19; } else if(streq(ptr1, "\tPOP BX\n\tSUB AX,BX\n\tNEG AX\n")) { ot("SUB AX,"); outstr(offset); outstr(" ;optim5 - 2"); nl(); ptr = ptr1 + 27; } else if(streq(ptr1, "\tPOP BX\n\tSUB AX,BX\n")) { ot("SUB AX,"); outstr(offset); nl(); ol("NEG AX ;optim5 - 3"); ptr = ptr1 + 19; } else if(streq(ptr1, "\tPOP BX\n\tCMP BX,AX\n")) { ot("CMP AX,"); outstr(offset); outstr(" ;optim5 - 4"); nl(); ptr = ptr1 + 19; } else if(streq(ptr1, "\tPOP BX\n\tXCHG AX,BX\n")) { ot("MOV BX,"); outstr(offset); outstr(" ;optim5 - 5"); nl(); ptr = ptr1 + 20; } else if(streq(ptr1, "\tPOP BX\n")) { ol("MOV BX,AX"); ot("MOV AX,"); outstr(offset); outstr(" ;optim5 - 6"); nl(); ptr = ptr1 + 8; } return ptr; } /* ** optimize strings beginning "\tPUSH AX\n\tLEA AX,[BP]" */ optim6(ptr, bump) char *ptr; int bump; { char offset[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save offset from LEA */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tMOV SI,AX\n\tMOV AX,[SI]\n\tPOP BX\n")) { ol("MOV BX,AX"); ot("MOV AX,[BP]"); outstr(offset); outstr(" ;optim6 - 1"); nl(); ptr = ptr1 + 32; } return ptr; } /* ** optimize strings beginning "\tMOV BX,DX\n\tPOP BX\n" */ optim7(ptr, bump) char *ptr; int bump; { ol(";optim7 - 1"); return ptr + 11; /* just skip over the useless part */ } /* ** optimize strings beginning "\tMOV BX," */ optim8(ptr, bump) char *ptr; int bump; { char offset[20], *ptr1, *ptr2; ptr1 = ptr + bump; /* skip text already recognized */ ptr2 = offset; while((*ptr2++ = *ptr1++) > ' ') ++bump; /* save offset from LEA */ *--ptr2 = 0; ++bump; ptr2 = ptr; /* save for compare */ if(streq(ptr1, "\tADD AX,BX\n")) { ot("ADD AX,"); outstr(offset); outstr(" ;optim8 - 1"); nl(); ptr = ptr1 + 11; } else if(streq(ptr1, "\tSUB AX,BX\n")) { ot("SUB AX,"); outstr(offset); outstr(" ;optim8 - 2"); nl(); ptr = ptr1 + 11; } return ptr; } 
C
#include <zephyr.h> #include <device.h> #include <drivers/gpio.h> #include "log.h" #include "backlight.h" #define LED_PORT DT_ALIAS_LED1_GPIOS_CONTROLLER #define LED DT_ALIAS_LED1_GPIOS_PIN struct device* backlight_dev; static bool backlight_enabled = false; void backlight_init(void) { LOG_DBG("Backlight starting..."); backlight_dev = device_get_binding(LED_PORT); gpio_pin_configure(backlight_dev, LED, GPIO_DIR_OUT); backlight_enable(true); LOG_INF("Backlight inited."); } void backlight_enable(bool enable) { gpio_pin_write(backlight_dev, LED, enable ? 0 : 1); backlight_enabled = enable; } bool backlight_is_enabled() { return backlight_enabled; }
C
/* ------------------------------------- Author: Anshul Khatri ID: 193313680 Email: khat3680@mylaurier.ca Version 2020-07-29 ------------------------------------- */ #ifndef GRAPH_H_ #define GRAPH_H_ #include "graph_components.h" #define BLOCK 5 #define True 1 #define False 0 typedef struct { int **matrix; //adjacency matrix Vertex * vertex_list; //list to store vertices (labels) int vertex_count; // number of vertices; int edge_count; // number of edges int directed; //flag : 0 undirected, 1 : directed int weighted; // flag: 0, non-weighted , 1: weighted }Graph; Graph* create_graph(int w, int d); void destroy_graph(Graph **g); void print_graph(Graph *g); int is_null_graph(Graph *g); int is_empty_graph(Graph *g); int add_vertex_graph(Graph *g, Vertex *v); int has_vertex_graph(Graph *g, Vertex *v); //int remove_vertex_graph(Graph *g,Vertex*v); int add_edge_graph(Graph *g, Edge *e); int has_edge_graph(Graph *g, Edge *e); int remove_edge_graph(Graph *g, Edge *e); #endif /* GRAPH_H_ */
C
#include <stdio.h> #include<stdlib.h> int verifica(int vetA[], int tamA, int vetB[], int tamB){ int i, j; for (i = 0 ; i < tamA ; i ++) for(j = 0; j < tamB ; j++) if (vetA[i] == vetB[j]) printf("%d, ", vetA[i]); } int main(){ int A[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31}; int n = sizeof(A)/sizeof(int); int B[] = {1, 2, 3, 4, 5, 6, 8, 10, 12, 7, 29}; int m = sizeof(B)/sizeof(int); verifica(A, n, B, m); return EXIT_SUCCESS; }
C
#include "fix_p_num.h" const fix_p_num fix_max = { FIXMAX, IWL_LIMIT }; const fix_p_num fix_min = { FIXMIN, IWL_LIMIT }; const fix_p_num one = { 0x40000000, 1 }; const fix_p_num zero = { 0, 1 }; void fix_p_num_min_int_len(fix_p_num* x) { unsigned int mask = 0x40000000; if (x == NULL) return; if (x->int_len < 2) return; if (x->value < 0) { // negative x->value = ~x->value; while (!(x->value & mask) && x->int_len > 1) { x->value <<= 1; x->int_len--; } x->value = ~x->value; } else { while (!(x->value & mask) && x->int_len > 1) { x->value <<= 1; x->int_len--; } } } static int fix_p_num_sign(fix_p_num* x) { return ((x->value >> 31) & 0x1); } static fix_p_num fix_p_num_abs(fix_p_num* fix) { struct fix_p_num result; result.int_len = fix->int_len; if(fix->value < 0) { result.value = -fix->value; return result; } result.value = fix->value; return result; } int fix_p_num_toi(fix_p_num* fix) { return((int)(fix->value >> (IWL_LIMIT - fix->int_len))); } static __inline__ fix_p_num fix_p_num_neg(fix_p_num* arg) { fix_p_num result; result.value = -arg->value; result.int_len = arg->int_len; return result; } fix_p_num fix_p_num_add(fix_p_num *x, fix_p_num *y) { struct fix_p_num result; unsigned short iwl = (x->int_len > y->int_len) ? x->int_len + 1 : y->int_len + 1; if (iwl > IWL_LIMIT) { return fix_max; } if (x->int_len > y->int_len) { result.value = (x->value >> 1) + (y->value >> (x->int_len - y->int_len + 1)); } else if (x->int_len < y->int_len) { result.value = (y->value >> 1) + (x->value >> (y->int_len - x->int_len + 1)); } else { //equal result.value = (x->value >> 1) + (y->value >> 1); } result.int_len = iwl; /* Set int len as small as possible */ fix_p_num_min_int_len(&result); return result; } fix_p_num fix_p_num_sub(fix_p_num *x, fix_p_num *y) { fix_p_num result; unsigned short iwl = (x->int_len > y->int_len) ? x->int_len + 1 : y->int_len + 1; if (iwl > IWL_LIMIT) { return fix_max; } if (x->int_len > y->int_len) { result.value = (x->value >> 1) - (y->value >> (x->int_len - y->int_len + 1)); } else if (x->int_len < y->int_len) { result.value = (x->value >> (y->int_len - x->int_len + 1)) - (y->value >> 1); } else { //equal result.value = (x->value >> 1) - (y->value >> 1); } result.int_len = iwl; /* Set int len as small as possible */ fix_p_num_min_int_len(&result); return result; } fix_p_num fix_p_num_mul(fix_p_num *x, fix_p_num *y) { fix_p_num result; fix_p_num tmp_x = {x->value, x->int_len}; fix_p_num tmp_y = {y->value, y->int_len}; unsigned short iwl = x->int_len + y->int_len; if (iwl > IWL_LIMIT) { if (fix_p_num_sign(x) ^ fix_p_num_sign(y)) { return fix_min; } else { return fix_max; } } if (iwl > x->int_len) { tmp_x.value >>= y->int_len; } if (iwl > y->int_len) { tmp_y.value >>= x->int_len; } result.int_len = iwl; result.value = tmp_x.value; __asm__ ( "imull %%ebx\n\t" /* multiply x*y, results are put in edx and ebx*/ "shrdl %%cl, %%edx, %%eax\n\t" /* shift frac part to maintain same frac part bit num */ :"=a"(result.value) :"a"(result.value), "b"(tmp_y.value), "c"(IWL_LIMIT-iwl) :"edx" ); fix_p_num_min_int_len(&result); return result; } fix_p_num fix_p_num_div(fix_p_num* x, fix_p_num *y) { fix_p_num result; fix_p_num tmp_x = fix_p_num_abs(x); fix_p_num tmp_y = fix_p_num_abs(y); unsigned short iwl = x->int_len; int sign; sign = fix_p_num_sign(x) ^ fix_p_num_sign(y); printf("%x, %d\n", tmp_y.value, tmp_y.int_len); if(y->value == 0) { /* divided by zero*/ if(sign) { return fix_min; } else { return fix_max; } } if (x->int_len > y->int_len) { tmp_y.value >>= (x->int_len-y->int_len); tmp_y.int_len += (x->int_len-y->int_len); iwl = x->int_len; if (tmp_y.value == 0) { if(sign) { return fix_min; } else { return fix_max; } } } else if (y->int_len > x->int_len) { tmp_x.value >>= (y->int_len-x->int_len); tmp_x.int_len += (y->int_len-x->int_len); iwl = y->int_len; if (tmp_x.value == 0) { result.value = 0; result.int_len = 1; return result; } } if(fix_p_num_toi(&tmp_y) == 0 || fix_p_num_toi(&tmp_y) == -1) { int tmp = tmp_y.value; /* * |y| < 1 */ tmp <<= tmp_y.int_len; while(!(tmp & (1 << IWL_LIMIT))) { tmp <<= 1; iwl++; } //iwl = iwl + x->int_len; if(iwl > IWL_LIMIT) { if(sign) { return fix_min; } else { return fix_max; } } } result.int_len = iwl; result.value = tmp_x.value; printf("%x, %d\n", result.value, result.int_len); __asm__ ( "xorl %%edx, %%edx\n\t" /* Clear edx */ "shldl %%cl, %%eax, %%edx\n\t" /* Shift edx left and fill in from eax */ "sall %%cl, %%eax\n\t" /* Shift eax upward */ "idivl %%ebx\n\t" /* Divide (edx:eax) / ebx */ :"=a"(result.value) :"a"(result.value), "b"(tmp_y.value), "c"(IWL_LIMIT-iwl) :"edx" ); fix_p_num_min_int_len(&result); if(sign) { return fix_p_num_neg(&result); } else { return result; } } int fix_init_d(fix_p_num *fix, double d) { unsigned int iwl = 1; int p = 1; if(!fix) { return 1; } /* * find out how many bits are needed to represent d. */ for(iwl = 1; iwl <= IWL_LIMIT; iwl++) { if(fabs(d) <= p) break; p <<= 1; } if(iwl > IWL_LIMIT) { if(d >= 0.) { *fix = fix_max; } else { *fix = fix_min; } } else { fix->int_len = iwl; fix->value = (int)(d * (1 << (IWL_LIMIT - fix->int_len))); } fix_p_num_min_int_len(fix); return 0; } int fix_p_num_gt(fix_p_num *x, fix_p_num *y) { int sign = fix_p_num_sign(x) ^ fix_p_num_sign(y); if (sign) { if (fix_p_num_sign(x) == 0) return 1; else return 0; } if (x->int_len > y->int_len || x->int_len == y->int_len && x->value > y->value) return 1; else return 0; } int fix_p_num_eq(fix_p_num *x, fix_p_num *y) { if (x->value == y->value && x->int_len == y->int_len) return 1; else 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 */ /* Variables and functions */ int /*<<< orphan*/ AUX_ENABLES ; int /*<<< orphan*/ AUX_MU_BAUD_REG ; int /*<<< orphan*/ AUX_MU_CNTL_REG ; int /*<<< orphan*/ AUX_MU_IER_REG ; int /*<<< orphan*/ AUX_MU_LCR_REG ; int /*<<< orphan*/ AUX_MU_MCR_REG ; int /*<<< orphan*/ GPFSEL1 ; int /*<<< orphan*/ GPPUD ; int /*<<< orphan*/ GPPUDCLK0 ; int /*<<< orphan*/ delay (int) ; unsigned int get32 (int /*<<< orphan*/ ) ; int /*<<< orphan*/ put32 (int /*<<< orphan*/ ,int) ; void uart_init(void) { unsigned int selector; selector = get32(GPFSEL1); selector &= ~(7 << 12); // clean gpio14 selector |= 2 << 12; // set alt5 for gpio14 selector &= ~(7 << 15); // clean gpio15 selector |= 2 << 15; // set alt5 for gpio15 put32(GPFSEL1, selector); put32(GPPUD, 0); delay(150); put32(GPPUDCLK0, (1 << 14) | (1 << 15)); delay(150); put32(GPPUDCLK0, 0); put32(AUX_ENABLES, 1); // Enable mini uart (this also enables access to it registers) put32(AUX_MU_CNTL_REG, 0); // Disable auto flow control and disable receiver // and transmitter (for now) put32(AUX_MU_IER_REG, 0); // Disable receive and transmit interrupts put32(AUX_MU_LCR_REG, 3); // Enable 8 bit mode put32(AUX_MU_MCR_REG, 0); // Set RTS line to be always high put32(AUX_MU_BAUD_REG, 270); // Set baud rate to 115200 put32(AUX_MU_CNTL_REG, 3); // Finally, enable transmitter and receiver }
C
#include "ping.h" struct proto proto_v4 = { proc_v4, send_v4, NULL, NULL, 0, IPPROTO_ICMP }; #ifdef IPV6 struct proto proto_v6 = { proc_v6, send_v6, NULL, NULL, 0, IPPROTO_ICMPV6 }; #endif int datalen = 56; /* data that goes with ICMP echo request */ int maxdatalen = 65507; int main(int argc, char **argv) { int c; struct addrinfo *ai; opterr = 0; /* don't want getopt() writing to stderr */ while ( (c = getopt(argc, argv, "vhbt:qc:i:s:ndw:S:W:fl:aA")) != -1) { switch (c) { case 'v': verbose++; break; case 'h': help(); break; case 'b': broadcast = 1; break; case 't': ttlcount = atoi(optarg); if (ttlcount < 1) err_quit("wrong input"); printf("time to live %d\n", ttlcount); break; case 'c': pingtimes = atoi(optarg); if (pingtimes < 0) err_quit("wrong input"); printf("ping %d times\n", pingtimes); break; case 'i': time_lag = atof(optarg); if (time_lag < 0.0) err_quit("wrong input"); printf("time lag %.3f s\n", time_lag); break; case 'q': printf("quiet mode. ctrl+c to stop\n"); quietmode = 1; break; case 's': datalen = atoi(optarg); if (datalen < 0) err_quit("wrong input"); if (datalen > maxdatalen) err_quit("packet size %d is too large. Maximum is %d", datalen, maxdatalen); break; case 'n': justnumber = 1; break; case 'd': sodebug = 1; break; case 'w': deadline = atoi(optarg); if (deadline < 0) err_quit("wrong input"); printf("deadline %d s\n", deadline); break; case 'W': time_out = atoi(optarg); break; case 'S': sndbuf = atoi(optarg); break; case 'f': flood = 1; break; case 'l': perload = atoi(optarg); if (perload < 1 || perload > 65536) err_quit("bad preload value, should be 1..65536"); break; case 'a': audio = 1; break; case 'A': auto_time = 1; break; case '?': err_quit("unrecognized option: %c", c); } } /*optind指向argv中未解释的参数的第一个*/ if (optind != argc-1) err_quit("usage: ping [ -v ] <hostname>"); host = argv[optind]; //格式正确时,argv[optind]为主机地址 pid = getpid(); signal(SIGALRM, sig_alrm); //为SIGALRM建立信号处理程序 /*这里开始处理主机名参数*/ ai = host_serv(host, NULL, 0, 0); /*addrinfo结构链表*/ if (broadcast) printf("WARNING: pinging broadcast address\n"); printf("ping %s (%s): %d data bytes\n", ai->ai_canonname, Sock_ntop_host(ai->ai_addr, ai->ai_addrlen), datalen); /* 根据协议初始化4initialize according to protocol */ if (ai->ai_family == AF_INET) { pr = &proto_v4; #ifdef IPV6 } else if (ai->ai_family == AF_INET6) { pr = &proto_v6; if (IN6_IS_ADDR_V4MAPPED(&(((struct sockaddr_in6 *) ai->ai_addr)->sin6_addr))) err_quit("cannot ping IPv4-mapped IPv6 address"); #endif } else err_quit("unknown address family %d", ai->ai_family); pr->sasend = ai->ai_addr; pr->sarecv = calloc(1, ai->ai_addrlen); pr->salen = ai->ai_addrlen; /*readloop处理分组*/ readloop(); exit(0); } void help(){ printf("Usage: ping \ [-aAbBdDfhLnOqrRUvV64] [-c count] [-i interval] [-I interface]\n \ \t\t[-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos]\n \ \t\t[-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option]\n \ \t\t[-w deadline] [-W timeout] [hop1 ...] destination\n\ Usage: ping -6 \ [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface]\n \ \t\t[-l preload] [-m mark] [-M pmtudisc_option]\n \ \t\t[-N nodeinfo_option] [-p pattern] [-Q tclass] [-s packetsize]\n \ \t\t[-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline]\n \ \t\t[-W timeout] destination\n"); } /*中断并输出汇总信息*/ void Stop(){ int i = 0; float sum = 0, max = rttmatrix[0], min = rttmatrix[0], avg = 0; for (i;i<nrecv;i++){ if (rttmatrix[i] > max) max = rttmatrix[i]; if (rttmatrix[i] < min) min = rttmatrix[i]; sum += rttmatrix[i]; } avg = sum/nrecv; printf("\n--- %s ping statistics ---\n", Sock_ntop_host(pr->sarecv, pr->salen)); printf("%u packets transmitted, %d received, %0.0f%% packet loss\n", nsent, nrecv, 1.0*(nsent-nrecv)/nsent*100); printf("rtt min/avg/max = %.3f/%.3f/%.3f/ ms\n", min, avg, max); close(sockfd); exit(0); } /*剥去ICMP报头*/ void proc_v4(char *ptr, ssize_t len, struct timeval *tvrecv) { int hlen1, icmplen; double rtt; struct ip *ip; struct icmp *icmp; struct timeval *tvsend; /*求ip报头长度,即ip报头长度标志乘4,头长度指明头中包含的4字节 *的个数。可接受的最小值是5,最大值是15*/ ip = (struct ip *) ptr; /* start of IP header */ hlen1 = ip->ip_hl << 2; /* length of IP header */ icmp = (struct icmp *) (ptr + hlen1); /*越过ip报头,指向ICMP报头*//* start of ICMP header */ if ( (icmplen = len - hlen1) < 8) /*len - hlen1为ICMP报头及ICMP数据报的总长度*/ err_quit("icmplen (%d) < 8", icmplen);/*小于ICMP报头长度则不合理*/ if (icmp->icmp_type == ICMP_ECHOREPLY) { if (icmp->icmp_id != pid) /*确保所接收的是发送的ICMP的回应*/ return; /* not a response to our ECHO_REQUEST */ if (icmplen < 16) err_quit("icmplen (%d) < 16", icmplen); tvsend = (struct timeval *) icmp->icmp_data; tv_sub(tvrecv, tvsend);/*接收和发送的时间差*/ rtt = tvrecv->tv_sec * 1000.0 + tvrecv->tv_usec / 1000.0;/*以毫秒为单位计算rtt*/ /*显示相关信息*/ if (!quietmode){ if (justnumber) printf("%d bytes from %s : seq=%u, ttl=%d, rtt=%.3f ms\n", icmplen, Sock_ntop_host(pr->sarecv, pr->salen), icmp->icmp_seq, ip->ip_ttl, rtt); else printf("%d bytes from %s(%s) : seq=%u, ttl=%d, rtt=%.3f ms\n", icmplen, Sock_ntop_host(pr->sarecv, pr->salen), Sock_ntop_host(pr->sarecv, pr->salen), icmp->icmp_seq, ip->ip_ttl, rtt); } rttmatrix[icmp->icmp_seq] = rtt; nrecv = icmp->icmp_seq + 1; // 统计接收数 } else if (verbose) { printf(" %d bytes from %s: type = %d, code = %d\n", icmplen, Sock_ntop_host(pr->sarecv, pr->salen), icmp->icmp_type, icmp->icmp_code); } } void proc_v6(char *ptr, ssize_t len, struct timeval* tvrecv) { #ifdef IPV6 int hlen1, icmp6len; double rtt; struct ip6_hdr *ip6; struct icmp6_hdr *icmp6; struct timeval *tvsend; /* ip6 = (struct ip6_hdr *) ptr; // start of IPv6 header hlen1 = sizeof(struct ip6_hdr); if (ip6->ip6_nxt != IPPROTO_ICMPV6) err_quit("next header not IPPROTO_ICMPV6"); icmp6 = (struct icmp6_hdr *) (ptr + hlen1); if ( (icmp6len = len - hlen1) < 8) err_quit("icmp6len (%d) < 8", icmp6len); */ icmp6=(struct icmp6_hdr *)ptr; if((icmp6len=len)<8) //len-40 err_quit("icmp6len (%d) < 8", icmp6len); if (icmp6->icmp6_type == ICMP6_ECHO_REPLY) { if (icmp6->icmp6_id != pid) return; /* not a response to our ECHO_REQUEST */ if (icmp6len < 16) err_quit("icmp6len (%d) < 16", icmp6len); tvsend = (struct timeval *) (icmp6 + 1); tv_sub(tvrecv, tvsend); rtt = tvrecv->tv_sec * 1000.0 + tvrecv->tv_usec / 1000.0; printf("%d bytes from %s: seq=%u, hlim=%d, rtt=%.3f ms\n", icmp6len, Sock_ntop_host(pr->sarecv, pr->salen), icmp6->icmp6_seq, ip6->ip6_hlim, rtt); } else if (verbose) { printf(" %d bytes from %s: type = %d, code = %d\n", icmp6len, Sock_ntop_host(pr->sarecv, pr->salen), icmp6->icmp6_type, icmp6->icmp6_code); } #endif /* IPV6 */ } /*校验和算法*/ unsigned short in_cksum(unsigned short *addr, int len) { int nleft = len; int sum = 0; unsigned short *w = addr; unsigned short answer = 0; /* * Our algorithm is simple, using a 32 bit accumulator (sum), we add * sequential 16 bit words to it, and at the end, fold back all the * carry bits from the top 16 bits into the lower 16 bits. */ /* 把ICMP报头二进制数据以2字节为单位累加起来*/ while (nleft > 1) { sum += *w++; nleft -= 2; } /*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个2字节数据 的高字节,这个2字节数据的低字节为0,继续累加*/ /* 4mop up an odd byte, if necessary */ if (nleft == 1) { *(unsigned char *)(&answer) = *(unsigned char *)w ; sum += answer; } /* 4add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = ~sum; /* truncate to 16 bits */ return(answer); } void send_v4(void) { int len; struct icmp *icmp; icmp = (struct icmp *) sendbuf; icmp->icmp_type = ICMP_ECHO; icmp->icmp_code = 0; icmp->icmp_id = pid; icmp->icmp_seq = nsent++; gettimeofday((struct timeval *) icmp->icmp_data, NULL);/*记录发送时间*/ len = 8 + datalen; /* checksum ICMP header and data */ icmp->icmp_cksum = 0; icmp->icmp_cksum = in_cksum((u_short *) icmp, len);/*校验算法*/ sendto(sockfd, sendbuf, len, 0, pr->sasend, pr->salen); } void send_v6() { #ifdef IPV6 int len; struct icmp6_hdr *icmp6; icmp6 = (struct icmp6_hdr *) sendbuf; icmp6->icmp6_type = ICMP6_ECHO_REQUEST; icmp6->icmp6_code = 0; icmp6->icmp6_id = pid; icmp6->icmp6_seq = nsent++; gettimeofday((struct timeval *) (icmp6 + 1), NULL); len = 8 + datalen; /* 8-byte ICMPv6 header */ sendto(sockfd, sendbuf, len, 0, pr->sasend, pr->salen); /* kernel calculates and stores checksum for us */ #endif /* IPV6 */ } void readloop(void) { int size; char recvbuf[BUFSIZE]; socklen_t len; ssize_t n; struct timeval tval; int yes = 1; /*创建套接口*/ sockfd = socket(pr->sasend->sa_family, SOCK_RAW, pr->icmpproto); setuid(getuid()); /* don't need special permissions any more */ size = 60 * 1024; /* OK if setsockopt fails */ //设置套接口缓冲区大小 setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); /* -t ******************** */ if (ttlcount) setsockopt(sockfd,IPPROTO_IP, IP_TTL, &ttlcount, sizeof(ttlcount)); /* -b */ if (broadcast) setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes)); /* -d */ if (sodebug) setsockopt(sockfd, SOL_SOCKET, SO_DEBUG, &yes, sizeof(yes)); /* -S */ if (sndbuf) setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)); /* -l */ while (perload > 0){ if (audio) printf("\a"); sig_alrm(SIGALRM); /*发送第一个分组 send first packet */ perload -= 1; } //读取返回给ICMP原始套接口的每个分组 for ( ; ; ) { len = pr->salen; n = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, pr->sarecv, &len); //小于0时返回错误 if (n < 0) { if (errno == EINTR) continue; else err_sys("recvfrom error"); } //记录收到分组的时间 gettimeofday(&tval, NULL); //调用proc来处理这些分组 if (audio) printf("\a"); (*pr->fproc)(recvbuf, n, &tval); /*中断*/ signal(SIGINT, Stop); /* -c */ if (pingtimes) if (nrecv == pingtimes) Stop(); /* -w */ if (deadline) if (nrecv * time_lag > deadline) Stop(); /* -W */ if (time_out) if (nrecv * time_lag * 1000 > time_out) Stop(); } } void sig_alrm(int signo) { struct itimerval it; memset(&it ,0x00,sizeof (it)); it.it_interval.tv_sec = 1; it.it_interval.tv_usec = 0; it.it_value.tv_sec = 1; it.it_value.tv_usec = 0; (*pr->fsend)(); /* -i */ if (time_lag != 1){ it.it_interval.tv_sec = (int)time_lag/1; it.it_interval.tv_usec = (time_lag-(int)time_lag/1) * 1000000; it.it_value.tv_sec = (int)time_lag/1; it.it_value.tv_usec = (time_lag-(int)time_lag/1) * 1000000; setitimer(ITIMER_REAL, &it, NULL); return; } /* -f */ if (flood || auto_time){ it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 10000; it.it_value.tv_sec = 0; it.it_value.tv_usec = 10000; setitimer(ITIMER_REAL, &it, NULL); return; } setitimer(ITIMER_REAL, &it, NULL); return; /* 可能会中断接收probably interrupts recvfrom() */ } /*计算接收和发送的时间差*/ void tv_sub(struct timeval *out, struct timeval *in) { if ( (out->tv_usec -= in->tv_usec) < 0) { /* out -= in */ --out->tv_sec; out->tv_usec += 1000000; } out->tv_sec -= in->tv_sec; } char * sock_ntop_host(const struct sockaddr *sa, socklen_t salen) { static char str[128]; /* Unix domain is largest */ switch (sa->sa_family) { case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *) sa; if (inet_ntop(AF_INET, &sin->sin_addr, str, sizeof(str)) == NULL) return(NULL); return(str); } #ifdef IPV6 case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa; if (inet_ntop(AF_INET6, &sin6->sin6_addr, str, sizeof(str)) == NULL) return(NULL); return(str); } #endif #ifdef HAVE_SOCKADDR_DL_STRUCT case AF_LINK: { struct sockaddr_dl *sdl = (struct sockaddr_dl *) sa; if (sdl->sdl_nlen > 0) snprintf(str, sizeof(str), "%*s", sdl->sdl_nlen, &sdl->sdl_data[0]); else snprintf(str, sizeof(str), "AF_LINK, index=%d", sdl->sdl_index); return(str); } #endif default: snprintf(str, sizeof(str), "sock_ntop_host: unknown AF_xxx: %d, len %d", sa->sa_family, salen); return(str); } return (NULL); } char * Sock_ntop_host(const struct sockaddr *sa, socklen_t salen) { char *ptr; if ( (ptr = sock_ntop_host(sa, salen)) == NULL) err_sys("sock_ntop_host error"); /* inet_ntop() sets errno */ return(ptr); } /*返回指针,指向由其中ai_next成员串联起来的addrinfo结构链表*/ struct addrinfo * host_serv(const char *host, const char *serv, int family, int socktype) { int n; struct addrinfo hints, *res; bzero(&hints, sizeof(struct addrinfo)); hints.ai_flags = AI_CANONNAME; /*指定如何来处理地址和名字*//* always return canonical name */ hints.ai_family = family; /*指定地址族*/ /* AF_UNSPEC, AF_INET, AF_INET6, etc. */ hints.ai_socktype = socktype; /*指定套接字的类型*//* 0, SOCK_STREAM, SOCK_DGRAM, etc. */ if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0) return(NULL); return(res); /* return pointer to first on linked list */ } /* end host_serv */ static void err_doit(int errnoflag, int level, const char *fmt, va_list ap) { int errno_save, n; char buf[MAXLINE]; errno_save = errno; /* value caller might want printed */ #ifdef HAVE_VSNPRINTF vsnprintf(buf, sizeof(buf), fmt, ap); /* this is safe */ #else vsprintf(buf, fmt, ap); /* this is not safe */ #endif n = strlen(buf); if (errnoflag) snprintf(buf+n, sizeof(buf)-n, ": %s", strerror(errno_save)); strcat(buf, "\n"); if (daemon_proc) { syslog(level, buf); } else { fflush(stdout); /* in case stdout and stderr are the same */ fputs(buf, stderr); fflush(stderr); } return; } /* Fatal error unrelated to a system call. * Print a message and terminate. */ void err_quit(const char *fmt, ...) { va_list ap; va_start(ap, fmt); err_doit(0, LOG_ERR, fmt, ap); va_end(ap); exit(1); } /* Fatal error related to a system call. * Print a message and terminate. */ void err_sys(const char *fmt, ...) { va_list ap; va_start(ap, fmt); err_doit(1, LOG_ERR, fmt, ap); va_end(ap); exit(1); }
C
/** @file interrupt.c @brief This file contains all interrupts. */ /* * interrupt.c * * Created on: May 24, 2018 * Author: ga76jid */ #include <util/delay.h> #include "interrupt.h" #include "io.h" #include "timer.h" /** This function activates interrupts on the provided pin. */ void config_rx_int(void){ PCMSK1 |= (1 << PCINT14); } /** This function deactivates interrupts on the provided pin. */ void disable_rx_int(void){ PCICR &= ~(1 << PCIE1); } /** This ISR sets the transmission pin according to the value of the tx_bit. */ ISR (TIMER1_COMPA_vect){ if(tx_request){ if(tx_bit) PORTB |= (1 << PINB6); else PORTB &= ~(1 << PINB6); } tx_request = 0; } void enable_rx_int(void){ PCICR |= (1 << PCIE1); } /** This ISR indicates indicates the receive method if a new bit can be read. */ ISR (TIMER2_COMPA_vect){ if(rx_active) rx_done = 1; } /** This ISR recognizes the start bit of the UART. */ ISR (PCINT1_vect){ if(!(PINB & (1 << PINB6))){ _delay_us(56); enable_Timer2(); reset_Timer2(); rx_active = 1; disable_rx_int(); } }
C
#include "polynomialRegression.h" #include "stdio.h" #include "stdlib.h" #include "assert.h" #include "math.h" void multiplyMatrices(int n, int y, int z, double firstInput[n][y], double secondInput[y][z], double output[n][z]){ for(int i = 0; i < n; i++){ for(int j = 0; j < z; j++){ double dotProduct = 0; for(int k = 0; k < y; k++){ dotProduct += firstInput[i][k] * secondInput[k][j]; } output[i][j] = dotProduct; } } } void matrixTranspose(int n, int k, double input[n][k], double output[k][n]){ for(int i = 0; i < n; i++){ for(int j = 0; j < k; j++){ output[j][i] = input[i][j]; } } } double determinant(int n, double input[n][n]){ if(n == 2){ return ((input[0][0] * input[1][1]) - (input[0][1] * input[1][0])); } else { double returnVal = 0; for(int i = 0; i < n; i++){ //extract the minors and recursively calculate their determinants double iMinor[n-1][n-1]; int p = 0; int q = 0; for(int k = 0; k < n; k++){ for(int j = 0; j < n; j++){ if(k!= 0 && j != i){ iMinor[p][q] = input[k][j]; if(q < (j-2)){ q++; } else { p = 0; q++; } } } } returnVal += pow(-1, i) * input[0][i] * determinant(n-1, iMinor); } return returnVal; } } void coFactorMatrix(int n, double input[n][n], double output[n][n]){ for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ //extract the minors and calculate their determinants double ijMinor[n-1][n-1]; int p = 0; int q = 0; for(int k = 0; k < n; k++){ for(int l = 0; l < n; l++){ if(k!= i && l != j){ ijMinor[p][q] = input[k][l]; if(q < (l-2)){ q++; } else { p = 0; q++; } } } } output[i][j] = pow(-1, i+j) * determinant(n-1, ijMinor); } } } void inverseMatrix(int n, double input[n][n], double output[n][n]){ double cofactors[3][3]; coFactorMatrix(n, input, cofactors); matrixTranspose(n, n, cofactors, output); double inputDeterminant = determinant(n, input); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ output[i][j] = output[i][j] / inputDeterminant; } } } void calculateCoefficients(int n, double xInput[n], double yInput[n], int polynomialOrder, double outputArray[polynomialOrder]){ assert(n >= polynomialOrder); //to ensure we have enough data to find all coeffiecients //create the matrix containing the powers of xInput as a 2-d array double xMatrixT[n][polynomialOrder]; for(int i = 0; i < polynomialOrder; i++){ for(int j = 0; j < n; j++){ xMatrixT[i][j] = pow(xInput[j], i); } } //convert the yInput into a 2d matrix we can work with double yMatrix[n][1]; for(int i = 0; i < n; i++){ yMatrix[i][0] = yInput[i]; } //calculate the coeffiecients by least squares double xMatrix[polynomialOrder][n]; matrixTranspose(n, polynomialOrder, xMatrixT, xMatrix); double xMatrixProduct[polynomialOrder][polynomialOrder]; multiplyMatrices(n, polynomialOrder, n, xMatrixT, xMatrix, xMatrixProduct); double xMatrixProductInverse[polynomialOrder][polynomialOrder]; inverseMatrix(polynomialOrder, xMatrixProduct, xMatrixProductInverse); double finalMatrix[polynomialOrder][n]; multiplyMatrices(polynomialOrder, n, n, xMatrixProductInverse, xMatrixT, finalMatrix); double finalCoefficients[polynomialOrder][1]; multiplyMatrices(polynomialOrder, n, 1, finalMatrix, yMatrix, finalCoefficients); for(int i = 0; i < polynomialOrder; i++){ outputArray[i] = finalCoefficients[i][0]; } } void testMultiplyMatrices(){ double firstInput[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; double secondInput[3][3] = {{10,11,12},{13,14,15},{16,17,18}}; double output[3][3]; multiplyMatrices(3,3,3,firstInput,secondInput,output); double testData[3][3] = {{84,90,96},{201,216,231},{318,342,366}}; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ assert(output[i][j] == testData[i][j]); } } printf("testMultiplyMatrices passed.\n"); } void testMatrixTranspose(){ double input[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; double output[3][3]; matrixTranspose(3, 3, input, output); double testData[3][3] = {{1,4,7},{2,5,8},{3,6,9}}; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ assert(output[i][j] == testData[i][j]); } } printf("testMatrixTranspose passed.\n"); } void testDeterminant(){ double input[3][3] = {{1,0,0},{0,1,0},{0,0,1}}; assert(determinant(3, input) == 1); double firstInput[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; assert(determinant(3, firstInput) == 0); double secondInput[4][4] = {{1,7,5,8},{5,1,4,6},{4,9,6,8},{4,9,6,2}}; assert((int)determinant(4, secondInput) == -462); printf("testDeterminant passed.\n"); } void testCoFactorMatrix(){ double input[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; double output[3][3]; coFactorMatrix(3, input, output); double testData[3][3] = {{-3,6,-3},{6,-12,6},{-3,6,-3}}; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ assert(output[i][j] == testData[i][j]); } } printf("testCoFactorMatrix passed.\n"); } void testInverseMatrix(){ //We'll test this case by multiply the matrix with it's inverse (because we've already //tested multiplication works) and checking that the result is the identity matrix double input[3][3] = {{1,7,5},{5,1,4},{4,9,6}}; double inverseInput[3][3]; double output[3][3]; inverseMatrix(3, input, inverseInput); multiplyMatrices(3,3,3,input, inverseInput, output); double testData[3][3] = {{1,0,0}, {0,1,0}, {0,0,1}}; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ assert((output[i][j] - testData[i][j]) < 0.1); } } printf("testInverseMatrix passed.\n"); } void testCalculateCoefficients(){ //y=2x ==> coefficients are 0,1,0 double xInput1[3] = {1,2,3}; double yInput1[3] = {2,4,6}; double output1[3]; calculateCoefficients(3, xInput1, yInput1, 3, output1); assert(output1[0] == 0); assert(output1[1] == 2); assert(output1[2] == 0); //y=(x^2)+1 ==> coefficients are 1,0,1 double xInput2[3] = {1,2,3}; double yInput2[3] = {2,5,10}; double output2[3]; calculateCoefficients(3, xInput2, yInput2, 3, output2); assert(output2[0] == 1); assert(output2[1] == 0); assert(output2[2] == 1); printf("testCalculateCoefficients passed.\n"); } void test(){ testMultiplyMatrices(); testMatrixTranspose(); testDeterminant(); testCoFactorMatrix(); testInverseMatrix(); testCalculateCoefficients(); printf("all tests passed.\n"); } int testMain(int n, char *args[n]){ test(); return 0; }
C
/* Give the 3rd dimension (N) of the array: 5 The matrix is : a b c d e f g h i j k l m n o p q r s t b c d e f g h i j k l m n o p q r s t u c d e f g h i j k l m n o p q r s t u v */ #include <stdio.h> #include <stdlib.h> int main(){ char *array[3][4]; int i, j, k, N; char input[12]; char gramma = 'a'; printf("Give the 3rd dimension (N) of the array: "); scanf("%s", input); N = atoi(input); while (N < 2){ printf("Lathos eisodos!\n"); scanf("%s", input); N = atoi(input); } for (i = 0 ; i < 3 ; i++){ for (j = 0 ; j < 4 ; j++){ array[i][j] = (char*)malloc(sizeof(char) * N); if (array[i][j] == NULL){ printf("malloc error\n"); return 1; } } } for (i = 0 ; i < 3 ; i++){ gramma = 'a' + i; for (j = 0 ; j < 4 ; j++){ for (k = 0 ; k < N ; k++){ array[i][j][k] = gramma++; } } } for (i = 0 ; i < 3 ; i++){ for (j = 0 ; j < 4 ; j++){ for (k = 0 ; k < N ; k++){ printf("%c ", array[i][j][k]); } printf("\n"); } printf("\n\n"); } for (i = 0 ; i < 3 ; i++){ for (j = 0 ; j < 4 ; j++){ free(array[i][j]); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include "trabajo.h" #include "servicio.h" #include "marca.h" #include "color.h" #include "fecha.h" #include "auto.h" int inicializarTrabajos(eTrabajo trabajo[], int tamT) { int error = 1; if(trabajo != NULL && tamT > 0) { for(int i = 0; i < tamT; i++) { trabajo[i].isEmpty = 1; } error = 0; } return error; } void mostrarTrabajo(eTrabajo trabajo, eServicio servicioT[], int tamT, int tamS) { char descServicio[60]; for(int i = 0; i < tamS; i++) { if(servicioT[i].id == trabajo.idServicio) { strcpy(descServicio, servicioT[i].descripcion); break; } } printf(" %5d %10s %10s %02d/%02d/%d\n", trabajo.id, trabajo.patente, descServicio, trabajo.fecha.dia, trabajo.fecha.mes, trabajo.fecha.anio); } int mostrarTrabajos(eTrabajo trabajo[], eServicio servicioT[], int tamT, int tamS) { int error = 1; int flag = 0; if(trabajo != NULL && tamT > 0) { printf(" *** Listado de Trabajos ***\n"); printf("------------------------------\n"); printf(" Id Patente ID Servicio Fecha\n"); for(int i = 0; i < tamT; i++) { if(trabajo[i].isEmpty == 0) { mostrarTrabajo(trabajo[i], servicioT, tamT, tamS); flag = 1; } } if( flag == 0) { printf(" No hay personas en la lista"); } printf("\n\n"); error = 0; } return error; } int buscarLibreTrabajo(eTrabajo trabajo[], int tamT)//carga el lugar libre que encuentre en indice { int indice = -1;//Si es -1 es que no hay lugares libres for(int i = 0; i < tamT; i++) { if(trabajo[i].isEmpty == 1) { indice = i; break;//Sin el break va a seguir buscando, solo queremos un lugar } } return indice; } int altaTrabajo(eTrabajo trabajo[], eServicio servicioT[], eAuto cocheT[], eMarca marcaT[], eColor colorT[], int tamT, int tamS, int tamA, int tamM, int tamC, int id) { int error = -1; int lugarVacio; char auxPatente[8]; int auxServicio; eTrabajo nuevoTrabajo; if(trabajo != NULL && tamT > 0 && id > 0) { system("cls"); printf(" *** ALTA DE TRABAJO ***\n\n"); lugarVacio = buscarLibreTrabajo(trabajo, tamT); if(lugarVacio == -1) { printf("ESTA LLENO, NO HAY LUGARES PARA TRABAJOS.\n\n"); } else { nuevoTrabajo.id = id; mostrarAutos(cocheT, marcaT, colorT, tamA); printf("Ingrese patente\n"); fflush(stdin); gets(auxPatente); while(validarPatente(cocheT, tamT, auxPatente) == 0) { printf("Patente invalida. Reingrese patente del auto: "); fflush(stdin); gets(auxPatente); } strcpy(nuevoTrabajo.patente, auxPatente); system("cls"); mostrarServicios(servicioT, tamS); printf("\nIngrese idServicio\n"); fflush(stdin); scanf("%d", &auxServicio); while(validarServicio(servicioT, tamS, auxServicio) == 0) { printf("Id Servicio invalido. Reingrese id Servicio: "); scanf("%d", &auxServicio); } nuevoTrabajo.idServicio = auxServicio; printf("\nIngrese fecha de inicio del trabajo\n"); fflush(stdin); scanf("%d/%d/%d", &nuevoTrabajo.fecha.dia, &nuevoTrabajo.fecha.mes, &nuevoTrabajo.fecha.anio); nuevoTrabajo.isEmpty = 0; trabajo[lugarVacio] = nuevoTrabajo; error = 0; } } return error; }
C
/* SPDX-License-Identifier: GPL-2.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <errno.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> int main(void) { char *const target = realpath("./signal", NULL); const struct test { const char *const name; char *const argv[4]; int signo; int want; } *t, tests[] = { { .name = "help option", .argv = {target, "-h", NULL}, .signo = 0, .want = 0, }, { .name = "10ms sleep", .argv = {target, "-t", "10", NULL}, .signo = SIGHUP, .want = 0, }, { .name = "SIGKILL with 10ms sleep", .argv = {target, "-t", "10", NULL}, .signo = SIGKILL, .want = 0, }, {.name = NULL}, /* sentry */ }; int ret = 0; for (t = tests; t->name; t++) { const union sigval si = {.sival_int = 0}; int status; pid_t pid; pid = fork(); if (pid == -1) { perror("fork"); return -1; } else if (pid == 0) { ret = execv(target, t->argv); if (ret == -1) { fprintf(stderr, "%s: %s", t->name, strerror(errno)); exit(EXIT_FAILURE); } } ret = sigqueue(pid, t->signo, si); if (ret == -1) { fprintf(stderr, "%s: %s", t->name, strerror(errno)); break; } ret = waitpid(pid, &status, 0); if (ret == -1) { fprintf(stderr, "%s: %s", t->name, strerror(errno)); break; } ret = -1; if (t->signo != 0 && !WIFSIGNALED(status)) { fprintf(stderr, "%s: child does not signaled\n", t->name); break; } if (t->signo == 0 && !WIFEXITED(status)) { fprintf(stderr, "%s: child does not exit\n", t->name); break; } if (WEXITSTATUS(status) != t->want) { fprintf(stderr, "%s: unexpected result:\n\t- want: %d\n\t- got: %d\n", t->name, t->want, WEXITSTATUS(status)); break; } ret = 0; } if (target) free((void *)target); if (ret) return 1; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "mpi.h" #include "functions.h" int main (int argc, char **argv) { MPI_Init(&argc,&argv); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD,&size); //seed value for the randomizer double seed = clock()+rank; //this will make your program run differently everytime //double seed = rank; //uncomment this and your program will behave the same everytime it's run srand(seed); //begin with rank 0 getting user's input unsigned int n; /* Q3.1 Make rank 0 setup the ELGamal system and broadcast the public key information */ //if(rank==0){ //printf("Enter a number of bits: "); fflush(stdout); // char status = scanf("%u",&n); //make sure the input makes sense // if ((n<3)||(n>31)) {//Updated bounds. 2 is no good, 31 is actually ok // printf("Unsupported bit size.\n"); // return 0; // } n = 5; printf("\n"); //} //declare storage for an ElGamal cryptosytem unsigned int p, g, h, x; //setup an ElGamal cryptosystem if(rank==0) setupElGamal(n,&p,&g,&h,&x); MPI_Bcast(&p,1,MPI_UNSIGNED,0,MPI_COMM_WORLD); MPI_Bcast(&g,1,MPI_UNSIGNED,0,MPI_COMM_WORLD); MPI_Bcast(&h,1,MPI_UNSIGNED,0,MPI_COMM_WORLD); //Suppose we don't know the secret key. Use all the ranks to try and find it in parallel if (rank==0) printf("Using %d processes to find the secret key...\n", size); /*Q3.2 We want to loop through values i=0 .. p-2 determine start and end values so this loop is distributed amounst the MPI ranks */ unsigned int N = p-1; //total loop size unsigned int start, end; unsigned int c = N/size; unsigned int r = N%size; if(rank <r) { start = rank*(c+1); end = start+c; } else{ start = rank*c +r; end=start+(c-1); } //loop through the values from 'start' to 'end' //double timeSt,timeEd; MPI_Barrier(MPI_COMM_WORLD); double timeSt=MPI_Wtime(); for (unsigned int i=start;i<end;i++) { if (modExp(g,i+1,p)==h) printf("Secret key found! x = %u\n",i+1); } MPI_Barrier(MPI_COMM_WORLD); double timeEd=MPI_Wtime(); long long int totalWork=size*(end-start); printf("Process %d took %f seconds with throughput %g\n",rank,timeEd-timeSt,totalWork/(timeEd-timeSt)); MPI_Finalize(); return 0; }
C
#include<stdio.h> #include<conio.h> void main() { int a; printf("enter the number"); scanf("%d",&a); if(a>0) { printf("%d is positive",a); } else if(a==0) { printf("%d is zero",a); } else { printf("%d is negative",a); } getch(); }
C
#include <stdio.h> #include <math.h> int main(){ int entrada; long int lado = 2 ; scanf("%d",&entrada); while(entrada>0){ lado = (lado + lado) - 1; entrada--; } printf("%ld\n",lado*lado); return 0; }
C
int a[5] = {2,3,6,8,9}, b[5] = {3,4,6,9,11}, c[5]; int i; void main() { for (i=0; i<5; i++) { c[i] = a[i] + b[i]; } assert(c[0] == 5, "c[0] must be 5"); assert(c[1] == 7, "c[1] must be 7"); assert(c[2] == 12, "c[2] must be 12"); assert(c[3] == 17, "c[3] must be 17"); assert(c[4] == 20, "c[4] must be 20"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_view_plane.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hcharlsi <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/25 11:24:11 by hcharlsi #+# #+# */ /* Updated: 2021/05/25 11:24:13 by hcharlsi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/minirt.h" t_vplane *get_view_plane(float width, float hight, float fov) { t_vplane *vplane; float aspect_ratio; vplane = malloc(sizeof(vplane)); if (!vplane) error_call(-1); aspect_ratio = width / hight; vplane->width = 2 * tan(fov / 2 * (M_PI / 180)); vplane->hight = vplane->width / aspect_ratio; vplane->x_pixel = vplane->width / width; vplane->y_pixel = vplane->hight / hight; return (vplane); }